【问题标题】:Using Time Span to compare two time intervals [closed]使用时间跨度比较两个时间间隔[关闭]
【发布时间】:2013-02-22 10:49:25
【问题描述】:

我想在某个时间和当前时间之间进行比较,以检查它是否超过了给定的时间段。

我认为我应该使用 TimeSpan,但我不确定如何使用。我比较的两个日期是 DateTime 对象。

 TimeSpan ts = TimeSpan.FromSeconds(_timeInterval);

 if(DateTime.UtcNow.Ticks - rex.LastFired.Ticks > ts.Ticks)
    // bla bla

【问题讨论】:

标签: c# datetime time


【解决方案1】:

只需将日期之间的差异与时间跨度进行比较。

var start = new DateTime(2013, 02, 15);
var now = DateTime.Now;

var oneWeek = new TimeSpan(7, 0, 0, 0);

if (now - start > oneWeek) {
    Console.Write("One week is passed since start date.");
} else {
    Console.Write("One week not yet passed since start date.");
}

【讨论】:

    【解决方案2】:
    if(DateTime.UtcNow - rex.LastFired > ts)
         ...
    

    【讨论】:

    • 我认为你必须使用rex.LastFired(没有.Ticks)。
    • @AlexFilipovici,是的,这就是我打算写的...谢谢
    【解决方案3】:

    为什么不使用 DateTime.Compare ?

    http://msdn.microsoft.com/en-us/library/system.datetime.compare.aspx

    编辑:您首先必须使用 TimeSpan.Substract 或 DateTime.Substract,然后您可以使用适当的 .Compare 方法。

    【讨论】:

      猜你喜欢
      • 2017-08-04
      • 1970-01-01
      • 2015-12-05
      • 2012-12-29
      • 1970-01-01
      • 2012-02-04
      • 1970-01-01
      • 1970-01-01
      • 2016-05-05
      相关资源
      最近更新 更多