F.B. ten Kate F.B. ten Kate - 1 year ago 78
C# Question

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.

Answer Source

Use DateTime.UtcNow instead of DateTime.Now EVERYWHERE

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download