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


C# DateTime.Subtract方法代码示例

本文整理汇总了C#中System.DateTime.Subtract方法的典型用法代码示例。如果您正苦于以下问题:C# DateTime.Subtract方法的具体用法?C# DateTime.Subtract怎么用?C# DateTime.Subtract使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.DateTime的用法示例。


在下文中一共展示了DateTime.Subtract方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetPercentTime

 /// <summary>
 ///     Returns a percentage of time elapsed from the assigned date to the due date
 /// </summary>
 /// <param name="assignedOn">Date assigned</param>
 /// <param name="dueOn">Date due</param>
 /// <returns>Normalized percent</returns>
 public static double GetPercentTime(DateTime assignedOn, DateTime dueOn)
 {
     TimeSpan totalTime = dueOn.Subtract(assignedOn);
     TimeSpan timeLeft = dueOn.Subtract(DateTime.Now);
     TimeSpan timeElapsed = totalTime.Subtract(timeLeft);
     return ((double) timeElapsed.Ticks / totalTime.Ticks);
 }
开发者ID:jkralicky,项目名称:TaskPlanner,代码行数:13,代码来源:Util.cs

示例2: Main

    static void Main()
    {
        DateTime start = new DateTime(2012, 1, 14);
        DateTime end = new DateTime(2013, 1, 25);

        if(start>end)
        {
            DateTime temp;
            temp = start;
            start = end;
            end = temp;
        }
        DateTime[] myDays = new DateTime[(int)end.Subtract(start).TotalDays];

        int daysToSubstract = 0;
        for (DateTime i = start; i <=end; )
        {
            for (int j = 0; j < holidays.Length; j++)
            {
                if(i==holidays[j])
                {
                    daysToSubstract++;
                }
            }
            if (i.DayOfWeek.ToString() == "Saturday" || i.DayOfWeek.ToString() == "Sunday")
            {
                daysToSubstract++;
            }
            i=i.AddDays(1);
        }

        Console.WriteLine("There are {0} days between {1:dd.MMMM.yyyy} and {2:dd.MMMM.yyyy}", end.Subtract(start).TotalDays,start,end);
        Console.WriteLine("{0} of these days are either a holiday or a weekend day",daysToSubstract);
        Console.WriteLine("So the total amount of work days is: {0}", end.Subtract(start).TotalDays-daysToSubstract);
    }
开发者ID:hackohackob,项目名称:TelerikAcademy,代码行数:35,代码来源:05.WorkDays.cs

示例3: KeyPerformanceIndicators

 public ActionResult KeyPerformanceIndicators(DateTime date)
 {
     dynamic data = new ExpandoObject();
     var orderVolume = salesDataWarehouseService.OrderVolume(date, date.Subtract(TimeSpan.FromDays(SalesHistoryDayRange)));
     data.RecentOrders = new ExpandoObject();
     data.RecentOrders.CurrentValue = orderVolume.Values.LastOrDefault();
     data.RecentOrders.HistoricalValues = orderVolume.Values.ToArray();
     var averageOrderValue = salesDataWarehouseService.AverageOrderValue(date, date.Subtract(TimeSpan.FromDays(SalesHistoryDayRange)));
     data.AverageOrderValue = new ExpandoObject();
     data.AverageOrderValue.CurrentValue = averageOrderValue.Values.LastOrDefault();
     data.AverageOrderValue.HistoricalValues = averageOrderValue.Values.ToArray();
     var uniqueCustomers = salesDataWarehouseService.UniqueCustomers(date, date.Subtract(TimeSpan.FromDays(SalesHistoryDayRange)));
     data.NewCustomerRatio = new ExpandoObject();
     data.NewCustomerRatio.CurrentValue = uniqueCustomers.Values.LastOrDefault().Item2;
     data.NewCustomerRatio.HistoricalValues = uniqueCustomers.Values.ToList().ConvertAll(item => item.Item1).ToArray();
     data.NewCustomerRatio.HistoricalUniqueCustomerValues = uniqueCustomers.Values.ToList().ConvertAll(item => item.Item2).ToArray();
     var uniqueSiteVisitors = salesDataWarehouseService.UniqueSiteVisitors(date, date.Subtract(TimeSpan.FromDays(SalesHistoryDayRange)));
     data.UniqueSiteVisitors = new ExpandoObject();
     data.UniqueSiteVisitors.CurrentValue = uniqueSiteVisitors.Values.LastOrDefault();
     data.UniqueSiteVisitors.HistoricalValues = uniqueSiteVisitors.Values.ToArray();
     return new JsonNetResult()
     {
         Data = data,
         HttpStatusCode = (int)System.Net.HttpStatusCode.OK,
         JsonRequestBehavior = JsonRequestBehavior.AllowGet
     };
 }
开发者ID:101v,项目名称:HTML5-Line-of-Business-Starter-Kit,代码行数:27,代码来源:HomeController.cs

示例4: GetClosestIndexByDate

        private int GetClosestIndexByDate(MarketSeries series, DateTime time)
        {
            var lastIndex = series.Close.Count - 1;

            if (time >= series.OpenTime[lastIndex])
                return lastIndex;

            var timeDifference = time.Subtract(series.OpenTime[0]);

            int index = 0;

            for (int i = 0; i < lastIndex - 1; i++)
            {
                if (time < series.OpenTime[i])
                    break;
                var currDiff = time.Subtract(series.OpenTime[i]);

                if (currDiff < timeDifference)
                {
                    timeDifference = currDiff;
                    index = i;
                }

            }

            return index;
        }
开发者ID:Mikai47,项目名称:cAlgoBot,代码行数:27,代码来源:Average+Daily+Range.cs

示例5: OutputDebugStringEventArgs

 internal OutputDebugStringEventArgs(int processId, DateTime messageTime, string messageText) {
     ProcessId = processId;
     MessageTime = messageTime;
     Message = messageText;
     SinceFirstEvent = messageTime.Subtract(Process.FirstMessageTime);
     SinceProcessStarted = messageTime.Subtract(Process.StartTime);
 }
开发者ID:roomaroo,项目名称:coapp.powershell,代码行数:7,代码来源:OutputDebugStringEventArgs.cs

示例6: PrepareInputSeries_ThreeSeries_LastOne_StartsLater

        public void PrepareInputSeries_ThreeSeries_LastOne_StartsLater()
        {
            TripletAnalyser tripletAnalyser = new TripletAnalyser();
            IList<string> symbolList = new List<string>();
            DateTime minDate = new DateTime(2000, 1, 1);
            DateTime maxDate = new DateTime(2001, 1, 1);
            string exchange = "Exchange";
            string symbol = "Symbol_1";

            IStoreOHLCVIntervals intervalRepository = MockRepository.GenerateStub<IStoreOHLCVIntervals>();

            intervalRepository.Stub(r => r.GetByTimeSpan(exchange, symbol, minDate, maxDate))
                .Return(GenerateInputSeriesList(symbol, minDate, maxDate.Subtract(minDate).Days));

            symbol = "Symbol_2";
            intervalRepository.Stub(r => r.GetByTimeSpan(exchange, symbol, minDate, maxDate))
                 .Return(GenerateInputSeriesList(symbol, minDate, maxDate.Subtract(minDate).Days));

            symbol = "Symbol_3";
            intervalRepository.Stub(r => r.GetByTimeSpan(exchange, symbol, minDate, maxDate))
                 .Return(GenerateInputSeriesList(symbol, minDate.AddDays(10), maxDate.Subtract(minDate).Days));

            List<double[]> intersection = tripletAnalyser.PrepareInputSeries(new List<string>() { "Exchange:Symbol_1", "Exchange:Symbol_2", "Exchange:Symbol_3" }, minDate, maxDate, intervalRepository);

            Assert.AreEqual(3, intersection.Count);
            Assert.AreEqual(356, intersection[0].Length);
            Assert.AreEqual(356, intersection[1].Length);
            Assert.AreEqual(356, intersection[2].Length);
            Assert.LessOrEqual(Double.Epsilon, Math.Abs(minDate.AddDays(10).Ticks - intersection[0][0]));
            Assert.LessOrEqual(Double.Epsilon, Math.Abs(maxDate.Ticks - intersection[0][355]));
        }
开发者ID:MattCollinge,项目名称:StrategyTester,代码行数:31,代码来源:TripletAnalyserTests.cs

示例7: DataAt

    public ThinkGearData DataAt(double secondsFromBeginning)
    {
        currentTime = DateTime.Now;

        deltaSeconds = currentTime.Subtract(startTime).TotalSeconds;

        elapsedSeconds += currentTime.Subtract(lastFrameTime).TotalSeconds;

        if(elapsedSeconds > BLINK_PERIOD){
          blinkValue = (int)(256.0f * (float)r.NextDouble());
          elapsedSeconds -= BLINK_PERIOD;
        }

        lastFrameTime = currentTime;

        return new ThinkGearData(secondsFromBeginning,
                             (int)(Math.Sin(deltaSeconds / 3.0f) * 50.0f + 50.0f),
                             (int)(Math.Cos(deltaSeconds / 3.0f) * 50.0f + 50.0f),
                             (int)(Math.Sin(deltaSeconds / 7.0f) * 50.0f + 50.0f),
                             0,
                             RandomValue(), RandomValue(),
                             RandomValue(), RandomValue(),
                             RandomValue(), RandomValue(),
                             RandomValue(), RandomValue(),
                             512.0f * (float)r.NextDouble(),
                             blinkValue);
    }
开发者ID:nicksteele,项目名称:MindeScape,代码行数:27,代码来源:FakeMindSetOutput.cs

示例8: Main

        static void Main(string[] args)
        {
            var d = new DateTime(1970, 1, 1);

            var unspecified = new DateTime(d.Ticks, DateTimeKind.Unspecified);
            var local = new DateTime(d.Ticks, DateTimeKind.Local);
            var localInUtc = DateTime.SpecifyKind(local, DateTimeKind.Utc);

            var utc = new DateTime(d.Ticks, DateTimeKind.Utc);

            Debug.WriteLine("un as local: " + unspecified.ToLocalTime().ToLongTimeString());
            Debug.WriteLine("lo as local: " + local.ToLocalTime().ToLongTimeString());
            Debug.WriteLine("ut as local: " + utc.ToLocalTime().ToLongTimeString());

            Debug.WriteLine("un as utc: " + unspecified.ToUniversalTime().ToLongTimeString());
            Debug.WriteLine("lo as utc: " + local.ToUniversalTime().ToLongTimeString());
            Debug.WriteLine("ut as utc: " + utc.ToUniversalTime().ToLongTimeString());

            TimeSpan ts = unspecified.Subtract(local);
            ts = unspecified.Subtract(utc);
            ts = local.Subtract(utc);

            local = DateTime.SpecifyKind(d, DateTimeKind.Local);
            utc = DateTime.SpecifyKind(d, DateTimeKind.Utc);

            var unspecifiedTicks = unspecified.Ticks;
            var localTicks = local.Ticks;
            var utcTicks = utc.Ticks;
        }
开发者ID:dhuffkc,项目名称:TestApps,代码行数:29,代码来源:Program.cs

示例9: ToUnsignedDbTicks

 public static ulong ToUnsignedDbTicks(DateTime d)
 {
     long dt = d.Subtract(JS_EPOCH).Ticks;
       if (dt < 0)
       {
     throw new Exception("Unsigned dbticks is negative");
       }
       return (ulong)(0.0001 * d.Subtract(JS_EPOCH).Ticks);
 }
开发者ID:Cycli,项目名称:Cycli,代码行数:9,代码来源:DbTime.cs

示例10: GetCurrentIntervalTime

 public static DateTime GetCurrentIntervalTime(DateTime lastTime, DateTime newTime, Interval interval)
 {
     if (newTime.Subtract(lastTime) < AppConst.AppTimeSpans[interval])
     {
         return lastTime;
     }
     else
     {
         while (newTime.Subtract(lastTime) >= AppConst.AppTimeSpans[interval])
         {
             lastTime = lastTime.Add(AppConst.AppTimeSpans[interval]);
         }
         return lastTime;
     }
 }
开发者ID:harryho,项目名称:demo-fx-trading-platform-prototype,代码行数:15,代码来源:AppUtil.cs

示例11: Calculate

	public void Calculate(){
		//define time points:
		startTime = new System.DateTime(1,1,1,(int)minValue,0,0,0);
		endTime = new System.DateTime(1,1,1,(int)maxValue,0,0,0);
				
		//correct 24 hour loop around:
		if (endTime.Subtract(startTime).Hours == 23) {
			endTime = startTime.AddDays(1);
		}else{
			endTime = endTime.AddHours(1);
		}
		
		//calculate duration:
		duration = endTime.Subtract(startTime);	
	}
开发者ID:bekpsmith,项目名称:pixelplacement,代码行数:15,代码来源:ActiveTimeRange.cs

示例12: Before

        /// <summary>
        /// Asserts that a <see cref="DateTime"/> occurs a specified amount of time before another <see cref="DateTime"/>.
        /// </summary>
        /// <param name="target">
        /// The <see cref="DateTime"/> to compare the subject with.
        /// </param>
        /// <param name="because">
        /// A formatted phrase explaining why the assertion should be satisfied. If the phrase does not 
        /// start with the word <i>because</i>, it is prepended to the message.
        /// </param>
        /// <param name="reasonArgs">
        /// Zero or more values to use for filling in any <see cref="string.Format(string,object[])"/> compatible placeholders.
        /// </param>
        public AndConstraint<DateTimeAssertions> Before(DateTime target, string because = "",
            params object[] reasonArgs)
        {
            bool success = Execute.Assertion
                .ForCondition(subject.HasValue)
                .BecauseOf(because, reasonArgs)
                .FailWith("Expected date and/or time {0} to be " + predicate.DisplayText +
                          " {1} before {2}{reason}, but found a <null> DateTime.",
                    subject, timeSpan, target);

            if (success)
            {
                var actual = target.Subtract(subject.Value);

                if (!predicate.IsMatchedBy(actual, timeSpan))
                {
                    Execute.Assertion
                        .BecauseOf(because, reasonArgs)
                        .FailWith(
                            "Expected date and/or time {0} to be " + predicate.DisplayText +
                            " {1} before {2}{reason}, but it differs {3}.",
                            subject, timeSpan, target, actual);
                }
            }

            return new AndConstraint<DateTimeAssertions>(parentAssertions);
        }
开发者ID:leijiancd,项目名称:fluentassertions,代码行数:40,代码来源:DateTimeRangeAssertions.cs

示例13: DateMinueDiff

 /// <summary>
 /// 时间段比较,返回已分钟为单位
 /// </summary>
 /// <param name="DateTime1"></param>
 /// <param name="DateTime2"></param>
 /// <returns></returns>
 public static string DateMinueDiff(DateTime DateTime1, DateTime DateTime2)
 {
     string dateDiff = "";
     TimeSpan ts = DateTime1.Subtract(DateTime2);
     dateDiff = ts.TotalMinutes.ToString();
     return dateDiff;
 }
开发者ID:Makk24,项目名称:GetHtmlPage,代码行数:13,代码来源:TypeParse.cs

示例14: AddActivityLog

 public bool AddActivityLog(int userID, DateTime date)
 {
     try
     {
         int discount = 0;
         UserActivityLog log = new UserActivityLog();
         if (log.GetLastActivityByUserID(userID))
         {
             // get between days only i.e.
             // last day 01/03/2015 - current date  04/03/2015
             // the between days not equal 3 it's only 2 ( 02/03/2015 - 03-03-2015 )
             // so diff = current date - last date - 1
             discount = date.Subtract(log.Date).Days - 1;
         }
         log.AddNew();
         log.ComboUserID = userID;
         log.Date = date;
         log.DaysToDiscount = discount;
         log.Save();
         // if save success
         return true;
     }
     catch (Exception ex)
     {
         //if save fail - duplicate entry
         return false;
     }
 }
开发者ID:menasbeshay,项目名称:ivalley-svn,代码行数:28,代码来源:combo.asmx.cs

示例15: GetBaseUnit

        private BaseUnit GetBaseUnit(DateTime dateFrom, DateTime dateTo)
        {
            var diff = dateTo.Subtract(dateFrom);
            var days = diff.TotalDays;
            var result = BaseUnit.Years;

            // Try to maintain groups count below TARGET_RESULT_SIZE
            if (diff.TotalMinutes < TARGET_RESULT_SIZE)
            {
                result = BaseUnit.Minutes;
            }
            else if (diff.TotalHours < TARGET_RESULT_SIZE)
            {
                result = BaseUnit.Hours;
            }
            else if (days < TARGET_RESULT_SIZE)
            {
                result = BaseUnit.Days;
            }
            else if (days / DAYS_PER_WEEK < TARGET_RESULT_SIZE)
            {
                result = BaseUnit.Weeks;
            }
            else if (days / DAYS_PER_MONTH < TARGET_RESULT_SIZE)
            {
                result = BaseUnit.Months;
            }

            return result;
        }
开发者ID:NoWHere80,项目名称:MobDict,代码行数:30,代码来源:VirtualizationController.cs


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