本文整理汇总了C#中System.TimeSpan.Negate方法的典型用法代码示例。如果您正苦于以下问题:C# TimeSpan.Negate方法的具体用法?C# TimeSpan.Negate怎么用?C# TimeSpan.Negate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.TimeSpan
的用法示例。
在下文中一共展示了TimeSpan.Negate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetSQLDatabaseChartData
private Task<ChartData> GetSQLDatabaseChartData(TimeSpan interval) {
var client = SQLDatabaseUsageClient.CreateServerUsagesClient(_path[0], SqlCredentialsProvider(_path[0]).Username, SqlCredentialsProvider(_path[0]).Password);
var usages = client.GetUsages(DateTime.UtcNow.Add(interval.Negate()));
var serverName = _path[0];
var counter = _path[_path.Length-1];
var database = _path[_path.Length-2];
switch(counter) {
case "logio":
return FilterSQLUsages(usages, serverName,database,"Log I/O","avg_log_write_percent");
case "dataio":
return FilterSQLUsages(usages, serverName,database,"Data I/O", "avg_physical_data_read_percent", "avg_data_io_percent");
case "cpu":
return FilterSQLUsages(usages, serverName,database, "CPU", "avg_cpu_percent");
case "storage":
return FilterSQLUsages(usages, serverName,database,"Storage", "storage_in_megabytes");
case "memory":
return FilterSQLUsages(usages, serverName,database,"Memory","active_memory_used_kb");
case "sessions":
return FilterSQLUsages(usages, serverName,database,"Sessions", "active_session_count");
default:
throw new Exception("Unknown counter " +counter);
}
}
示例2: GetMetricsForResourceId
//the limit seems to be 2880 metrics per request
async System.Threading.Tasks.Task<ICollection<MetricValueSet>> GetMetricsForResourceId(string resourceId, TimeSpan forHistory, MetricsFilter filter) {
var metricsResult = await MetricsClientFacade.ListDefinitionsAsync(_credentials, resourceId,null,null);
var metrics = filter.FilterMetrics(metricsResult.MetricDefinitionCollection.Value.Where(_=>_.MetricAvailabilities.Any()).ToList());
if(!metrics.Any()) {
return new MetricValueSet[0];
}
var minTimeGrain = metrics.SelectMany(_=>_.MetricAvailabilities.Where(ma=>forHistory<ma.Retention).Select(a=>a.TimeGrain)).Min();
var metricNames = metrics.Select(_=>_.Name).ToList();
var till = DateTime.UtcNow.AddMinutes(1);
var from = till.Add(forHistory.Negate());
return await Fetch(new FetchData {
ResourceId = resourceId,
MetricNames = metricNames,
TimeGrain = minTimeGrain,
From = from,
Till = till
});
}
示例3: Update
public void Update(TimeSpan total)
{
total = total.Subtract(Map01.start);
if (total.Ticks < 0)
total = total.Negate();
time = total.Minutes + ":" + total.Seconds.ToString("00.") + ":" + total.Milliseconds;
}
示例4: PosTest1
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Call Negate when current TimeSpan is a positive value");
try
{
long randValue = 0;
do
{
randValue = TestLibrary.Generator.GetInt64(-55);
} while (randValue <= 0);
TimeSpan expected = new TimeSpan(randValue);
TimeSpan res = expected.Negate();
if (res.Ticks != (expected.Ticks * -1))
{
TestLibrary.TestFramework.LogError("001.1", "Call Negate when current TimeSpan is a positive value does not return a negative value");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] res.Ticks = " + res.Ticks + ", expected.Ticks = " + expected.Ticks + ", expected = " + expected + ", randValue = " + randValue);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
示例5: AbsTimeSpan
/// <summary>
/// Returns the absolute value of the specified TimeSpan.
/// </summary>
/// <param name="val">The val.</param>
/// <returns></returns>
public static TimeSpan AbsTimeSpan(TimeSpan val)
{
if (IsTimeSpanNegative(val))
{
val = val.Negate();
}
return val;
}
示例6: GetTime
string GetTime( TimeSpan input )
{
bool inThePast = input < TimeSpan.Zero;
if ( inThePast )
input = input.Negate();
return string.Format( new PluralizeFormatProvider(), "{0:day/days}, {1:hour/hours}, {2:minute/minutes}, {3:second/seconds} {4}", input.Days, input.Hours, input.Minutes, input.Seconds, inThePast ? "ago" : "" );
}
示例7: BuildMongodumpArguments
private IEnumerable<Tuple<string, string>> BuildMongodumpArguments(TimeSpan timeAgo)
{
var epoch = new DateTime(1970, 1, 1).ToUniversalTime();
var startTime = (long)DateTime.UtcNow.Add(timeAgo.Negate()).Subtract(epoch).TotalMilliseconds;
yield return new Tuple<string, string>("products", string.Format("\"{{UpdateTime: {{$gt: new Date({0})}}}}\"", startTime));
yield return new Tuple<string, string>("categories", null);
//yield return new Tuple<string, string>("ratio_rankings", null);
}
示例8: ParseExactTest
public static void ParseExactTest(string inputTimeSpan, string format, TimeSpan expectedTimeSpan)
{
TimeSpan actualTimeSpan = TimeSpan.ParseExact(inputTimeSpan, format, new CultureInfo("en-US"));
Assert.Equal(expectedTimeSpan, actualTimeSpan);
bool parsed = TimeSpan.TryParseExact(inputTimeSpan, format, new CultureInfo("en-US"), out actualTimeSpan);
Assert.True(parsed);
Assert.Equal(expectedTimeSpan, actualTimeSpan);
// TimeSpanStyles is interpreted only for custom formats
if (format != "c" && format != "g" && format != "G")
{
actualTimeSpan = TimeSpan.ParseExact(inputTimeSpan, format, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative);
Assert.Equal(expectedTimeSpan.Negate(), actualTimeSpan);
parsed = TimeSpan.TryParseExact(inputTimeSpan, format, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative, out actualTimeSpan);
Assert.True(parsed);
Assert.Equal(expectedTimeSpan.Negate(), actualTimeSpan);
}
}
示例9: Subtract
// ----------------------------------------------------------------------
public virtual DateTime? Subtract( DateTime start, TimeSpan offset, SeekBoundaryMode seekBoundaryMode = SeekBoundaryMode.Next )
{
if ( includePeriods.Count == 0 && excludePeriods.Count == 0 )
{
return start.Subtract( offset );
}
TimeSpan? remaining;
return offset < TimeSpan.Zero ?
CalculateEnd( start, offset.Negate(), SeekDirection.Forward, seekBoundaryMode, out remaining ) :
CalculateEnd( start, offset, SeekDirection.Backward, seekBoundaryMode, out remaining );
}
示例10: AcquireLock
private int AcquireLock(string resource, TimeSpan timeout)
{
return
_connection
.Execute(
"INSERT INTO DistributedLock (Resource, CreatedAt) " +
" SELECT @resource, @now " +
" FROM dual " +
" WHERE NOT EXISTS ( " +
" SELECT * FROM DistributedLock " +
" WHERE Resource = @resource " +
" AND CreatedAt > @expired)",
new
{
resource,
now = DateTime.UtcNow,
expired = DateTime.UtcNow.Add(timeout.Negate())
});
}
示例11: Subtract
/// <summary>
/// <paramref name="start"/> 시각으로부터 <paramref name="offset"/> 기간을 뺀 (즉 이전의) 시각을 계산합니다.
/// </summary>
/// <param name="start">시작 시각</param>
/// <param name="offset">기간(Duration)</param>
/// <param name="seekBoundaryMode">검색시 경계에 대한 모드</param>
/// <returns></returns>
public virtual DateTime? Subtract(DateTime start, TimeSpan offset, SeekBoundaryMode seekBoundaryMode = SeekBoundaryMode.Next) {
if(IsDebugEnabled)
log.Debug("Start 시각[{0}] + Duration[{1}]의 시각을 계산합니다.... SeekBoundaryMode=[{2}]", start, offset, seekBoundaryMode);
if(IncludePeriods.Count == 0 && ExcludePeriods.Count == 0)
return start.Subtract(offset);
TimeSpan? remaining;
var end = offset < TimeSpan.Zero
? CalculateEnd(start, offset.Negate(), SeekDirection.Forward, seekBoundaryMode, out remaining)
: CalculateEnd(start, offset, SeekDirection.Backward, seekBoundaryMode, out remaining);
if(IsDebugEnabled)
log.Debug("Start 시각[{0}] + Duration[{1}]의 시각 End=[{2}], remaining=[{3}] 입니다!!! SeekBoundaryMode=[{4}]",
start, offset, end, remaining, seekBoundaryMode);
return end;
}
示例12: TestToFromTimeSpan
public void TestToFromTimeSpan()
{
Random r = new Random();
string[] formats =
new string[]
{
"{0}",
"{1}",
"0x{1:x16}",
"stuff b4{1}1morestuffafter",
"{2}{3} {4:d2}:{5:d2}:{6:d2}.{7:d3}ms",
"{2}{3}d {4}h {5}m {6}s {7}ms",
"{8} days",
"{9} hours",
"{10:f10} minutes",
"Total seconds: {11:n3}",
"{12}ms",
};
for (int i = 0; i < 10000; i++)
{
long ticks = (((long)r.Next(2048) << 30) + r.Next());
ticks -= ticks % TimeSpan.TicksPerMillisecond; // round to nearest ms
TimeSpan value = new TimeSpan(ticks);
foreach (var fmt in formats)
{
string text = TypeConverter.Instance.ToString(value, fmt, null);
TimeSpan result = TypeConverter.Instance.ParseTimeSpan(text, fmt, null);
if (i == 0) Trace.TraceInformation("{0} => {1} == {2}", value, fmt, text);
Assert.AreEqual(value.Ticks, result.Ticks);
TimeSpan neg = value.Negate();
text = TypeConverter.Instance.ToString(neg, fmt, null);
result = TypeConverter.Instance.ParseTimeSpan(text, fmt, null);
if (i == 0) Trace.TraceInformation("{0} => {1} == {2}", value, fmt, text);
Assert.AreEqual(neg.Ticks, result.Ticks);
}
}
}
示例13: BatchConvertSave
internal static bool BatchConvertSave(string toFormat, string offset, Encoding targetEncoding, string outputFolder, int count, ref int converted, ref int errors, IList<SubtitleFormat> formats, string fileName, Subtitle sub, SubtitleFormat format, bool overwrite, string pacCodePage)
{
// adjust offset
if (!string.IsNullOrEmpty(offset) && (offset.StartsWith("/offset:") || offset.StartsWith("offset:")))
{
string[] parts = offset.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 5)
{
try
{
TimeSpan ts = new TimeSpan(0, int.Parse(parts[1].TrimStart('-')), int.Parse(parts[2]), int.Parse(parts[3]), int.Parse(parts[4]));
if (parts[1].StartsWith("-"))
sub.AddTimeToAllParagraphs(ts.Negate());
else
sub.AddTimeToAllParagraphs(ts);
}
catch
{
Console.Write(" (unable to read offset " + offset + ")");
}
}
}
bool targetFormatFound = false;
string outputFileName;
foreach (SubtitleFormat sf in formats)
{
if (sf.Name.ToLower().Replace(" ", string.Empty) == toFormat.ToLower() || sf.Name.ToLower().Replace(" ", string.Empty) == toFormat.Replace(" ", string.Empty).ToLower())
{
targetFormatFound = true;
sf.BatchMode = true;
outputFileName = FormatOutputFileNameForBatchConvert(fileName, sf.Extension, outputFolder, overwrite);
Console.Write(string.Format("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName));
if (sf.IsFrameBased && !sub.WasLoadedWithFrameNumbers)
sub.CalculateFrameNumbersFromTimeCodesNoCheck(Configuration.Settings.General.CurrentFrameRate);
else if (sf.IsTimeBased && sub.WasLoadedWithFrameNumbers)
sub.CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate);
File.WriteAllText(outputFileName, sub.ToText(sf), targetEncoding);
if (format.GetType() == typeof(Sami) || format.GetType() == typeof(SamiModern))
{
var sami = (Sami)format;
foreach (string className in Sami.GetStylesFromHeader(sub.Header))
{
var newSub = new Subtitle();
foreach (Paragraph p in sub.Paragraphs)
{
if (p.Extra != null && p.Extra.ToLower().Trim() == className.ToLower().Trim())
newSub.Paragraphs.Add(p);
}
if (newSub.Paragraphs.Count > 0 && newSub.Paragraphs.Count < sub.Paragraphs.Count)
{
string s = fileName;
if (s.LastIndexOf('.') > 0)
s = s.Insert(s.LastIndexOf('.'), "_" + className);
else
s += "_" + className + format.Extension;
outputFileName = FormatOutputFileNameForBatchConvert(s, sf.Extension, outputFolder, overwrite);
File.WriteAllText(outputFileName, newSub.ToText(sf), targetEncoding);
}
}
}
Console.WriteLine(" done.");
}
}
if (!targetFormatFound)
{
var ebu = new Ebu();
if (ebu.Name.ToLower().Replace(" ", string.Empty) == toFormat.ToLower())
{
targetFormatFound = true;
outputFileName = FormatOutputFileNameForBatchConvert(fileName, ebu.Extension, outputFolder, overwrite);
Console.Write(string.Format("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName));
ebu.Save(outputFileName, sub);
Console.WriteLine(" done.");
}
}
if (!targetFormatFound)
{
var pac = new Pac();
if (pac.Name.ToLower().Replace(" ", string.Empty) == toFormat.ToLower() || toFormat.ToLower() == "pac" || toFormat.ToLower() == ".pac")
{
pac.BatchMode = true;
if (!string.IsNullOrEmpty(pacCodePage) && Utilities.IsInteger(pacCodePage))
pac.CodePage = Convert.ToInt32(pacCodePage);
targetFormatFound = true;
outputFileName = FormatOutputFileNameForBatchConvert(fileName, pac.Extension, outputFolder, overwrite);
Console.Write(string.Format("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName));
pac.Save(outputFileName, sub);
Console.WriteLine(" done.");
}
}
if (!targetFormatFound)
{
var cavena890 = new Cavena890();
if (cavena890.Name.ToLower().Replace(" ", string.Empty) == toFormat.ToLower())
{
targetFormatFound = true;
outputFileName = FormatOutputFileNameForBatchConvert(fileName, cavena890.Extension, outputFolder, overwrite);
Console.Write(string.Format("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName));
cavena890.Save(outputFileName, sub);
//.........这里部分代码省略.........
示例14: ToTimeSpan
public static TimeSpan ToTimeSpan(string input)
{
const string pattern = @"(?<sign>[+|-])?P((?<years>\d+)Y)?((?<months>\d+)M)?((?<days>\d+)D)?(T((?<hours>\d+)H)?((?<minutes>\d+)M)?((?<seconds>\d+(\.\d+)?)S)?)?";
var regEx = new Regex(pattern);
var match = regEx.Match(input);
if (!match.Success)
{
throw new FormatException(string.Format("JSON TimeSpan '{0}' cannot be parsed", input));
}
bool neg = false;
int days = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
int milliseconds = 0;
var sign = match.Groups["sign"];
if (sign.Success && sign.Value == "-")
{
neg = true;
}
//currently we do not support years and months (.NET never uses them)
if (match.Groups["years"].Success || match.Groups["months"].Success) throw new FormatException(string.Format("JSON TimeSpan '{0}' cannot be parsed, year or month included", input));
var daysGroup = match.Groups["days"];
if (daysGroup.Success)
{
days = int.Parse(daysGroup.Value);
}
var hoursGroup = match.Groups["hours"];
if (hoursGroup.Success)
{
hours = int.Parse(hoursGroup.Value);
}
var minutesGroup = match.Groups["minutes"];
if (minutesGroup.Success)
{
minutes = int.Parse(minutesGroup.Value);
}
var secondsGroup = match.Groups["seconds"];
if (secondsGroup.Success)
{
var secondsAndMillis = double.Parse(secondsGroup.Value);
seconds = (int) Math.Floor(secondsAndMillis);
milliseconds = (int) Math.Round(((secondsAndMillis - seconds)*1000));
}
var timeSpan = new TimeSpan(days, hours, minutes, seconds, milliseconds);
return neg ? timeSpan.Negate() : timeSpan;
}
示例15: WriteTimeZone
private static void WriteTimeZone(StringBuilder sb, TimeSpan zone)
{
bool negTimeZone = true;
if (zone.Ticks < 0)
{
negTimeZone = false;
zone = zone.Negate();
}
WriteTimeZone(sb, negTimeZone, zone.Hours, zone.Minutes);
}