开发者

Does Daylightsaving time cause DateTime calculations to become negative

We are currently rewritting the core of our services, basically we have scheduled tasks that can run on intervals, dates, specific times etc etc etc.

Currently we're wondering if daylightsaving might cause trouble for us, basically we calculate the next possible runtime, based on what days the task should execute and between what times, and what interval. We do this by taking the current time, and adding days/minutes/hours to this DateTime.

We then take this new run time and subtract DateTime.Now from this DateTime, leaving us with the timespan untill the next run.

How ever, what if the current time is 01:50 on a daylightsavings day, we add 20 minutes, which is our set interval, and end up with a time of 02:10, how ever since this is daylightsavinds, it's actually 01:10.

When i subtract the current time (01:50) from the 01:10 (which is actually 02:10) does this return a negative value which i need to work around or does this never ever return a negative value because DateTime is just a long underneath holding the proper information?

Basically, the following code, is the check needed or not?

//Get interval between nextrun and right now!
double interval = (NextRun - DateTime.Now).TotalMilliseconds;

//Check if interval is ever less or equal to 0, should never happen but maybe with daylight saving time?
if(interval <= 0)
{
    //Set 开发者_开发百科default value
    interval = IntervalInMilliseconds;
}

We believe that this check isn't needed but our googling so far hasn't given us a definative answer.


Use DateTime.UtcNow instead of DateTime.Now EVERYWHERE


First of all, you can try it yourself as it will help you understand how it works.

Essentially, using your example above, if you have 20 minutes to a local time, it would be 2:10 and not 1:10 as the computation is done in local time. If you want to get 1:10, you need to convert local time to universal time, add 20 minutes and then convert back to local time.

If you want real elapsed time, then you have to convert time to universal time before computing time difference. Also, if you work in local time, you won't be able to differentiate ambiguous time when the clock goes back.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜