开发者

Date comparison - How to check if 20 minutes have passed?

How to check if 20 minutes have passed from current date?

For example:

var start开发者_如何学JAVA = DateTime.Now;
var oldDate = "08/10/2011 23:50:31"; 

    if(start ??) {
     //20 minutes were passed from start
    }

what's the best way to do this? Thanks :)


  1. You should convert your start time to a UTC time, say 'start'.

  2. You can now compare your start time to the current UTC time using:

    DateTime.UtcNow > start.AddMinutes(20)

This approach means that you will get the correct answer around daylight savings time changes.

By adding time to the start time instead of subtracting and comparing the total time on a TimeSpan you have a more readable syntax AND you can handle more date difference cases, e.g. 1 month from the start, 2 weeks from the start, ...


var start = DateTime.Now;
var oldDate = DateTime.Parse("08/10/2011 23:50:31");

if ((start - oldDate).TotalMinutes >= 20)
{
    //20 minutes were passed from start  
}


var start = DateTime.Now;
var oldDate = DateTime.Parse("08/10/2011 23:50:31"); 

    if(start.Subtract(oldDate) >= TimeSpan.FromMinutes(20)) 
    {
     //20 minutes were passed from start
    }


Parse oldDate into a DateTime object (DateTime.Parse).

Subtract the parsed date from start. This will return a TimeSpan.

Inspect TotalMinutes.


I was able to accomplish this by using a JodaTime Library in my project. I came out with this code.

String datetime1 = "2012/08/24 05:22:34";
String datetime2 = "2012/08/24 05:23:28";

DateTimeFormatter format = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss");
DateTime time1 = format.parseDateTime(datetime1);
DateTime time2 = format.parseDateTime(datetime2);
Minutes Interval = Minutes.minutesBetween(time1, time2);
Minutes minInterval = Minutes.minutes(20);

if(Interval.isGreaterThan(minInterval)){
  return true;
}
else{
  return false;
}

This will check if the Time Interval between datetime1 and datetime2 is GreaterThan 20 Minutes. Change the property to Seconds. It will be easier for you know. This will return false.


var end = DateTime.Parse(oldDate);   
 if (start.Hour == end.Hour && start.AddMinutes(20).Minute >= end.Minute)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜