Using Time Span to compare two time intervals [clo

2020-07-26 15:13发布

I want to compare between a certain time and the current time to check if it has exceeded a given period.

I think i should be using TimeSpan but i am not sure how. The two dates im comparing are DateTime objects.

 TimeSpan ts = TimeSpan.FromSeconds(_timeInterval);

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

标签: c# datetime time
3条回答
倾城 Initia
2楼-- · 2020-07-26 15:20
if(DateTime.UtcNow - rex.LastFired > ts)
     ...
查看更多
仙女界的扛把子
3楼-- · 2020-07-26 15:29

Just compare the difference between your dates with a timespan.

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.");
}
查看更多
ら.Afraid
4楼-- · 2020-07-26 15:38

Why not use the DateTime.Compare ?

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

EDIT: you ll first have to use TimeSpan.Substract or DateTime.Substract, then you can use the appropiate .Compare method.

查看更多
登录 后发表回答