当前位置: 首页>>代码示例>>C#>>正文


C# TimeSpan.Negate方法代码示例

本文整理汇总了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);
            }
        }
开发者ID:santosh-mnrec,项目名称:AzurePlot,代码行数:25,代码来源:ChartDataFacade.cs

示例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
            });
		}
开发者ID:santosh-mnrec,项目名称:AzurePlot,代码行数:26,代码来源:AzureMetricsApiClient.cs

示例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;
 }
开发者ID:HanHangit,项目名称:2D-Spiel,代码行数:7,代码来源:Hud.cs

示例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;
    }
开发者ID:l1183479157,项目名称:coreclr,代码行数:34,代码来源:timespannegate.cs

示例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;
 }
开发者ID:Yitzchok,项目名称:PublicDomain,代码行数:13,代码来源:DateTimeUtlities.cs

示例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" : "" );
        }
开发者ID:jimmydorry,项目名称:steam-irc-bot,代码行数:9,代码来源:TI4.cs

示例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);
        }
开发者ID:keily,项目名称:LightOne,代码行数:10,代码来源:DatabaseExport.cs

示例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);
        }
    }
开发者ID:shiftkey-tester,项目名称:corefx,代码行数:20,代码来源:TimeSpan.cs

示例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 );
        }
开发者ID:jwg4,项目名称:date-difference,代码行数:13,代码来源:DateAdd.cs

示例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())
                 });
 }
开发者ID:arnoldasgudas,项目名称:Hangfire.MySqlStorage,代码行数:19,代码来源:MySqlDistributedLock.cs

示例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;
        }
开发者ID:debop,项目名称:NFramework,代码行数:26,代码来源:DateAdd.cs

示例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);
                }
            }
        }
开发者ID:modulexcite,项目名称:NClassify,代码行数:42,代码来源:TestConverter.cs

示例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);
//.........这里部分代码省略.........
开发者ID:IlgnerBri,项目名称:subtitleedit,代码行数:101,代码来源:Main.cs

示例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;
        }
开发者ID:nguyenkien,项目名称:api,代码行数:56,代码来源:JsonConvert.cs

示例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);
 }
开发者ID:chcosta,项目名称:corefx,代码行数:10,代码来源:SqlUtils.cs


注:本文中的System.TimeSpan.Negate方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。