The following c# code is supposed to return a timespan that indicates how much time there is between the current time and the next occurence of an event, supposed to happen at 5am. It must handle the case when the code is called before or after 5am.
The code manages to return negative delays on our servers (+1GMT) between 4 and 5am, which I cannot comprehend. Would anyone know what the explanation is ?
TimeSpan EverydayAt(int hourOfDay)
{
DateTimeOffset now = DateTimeOffset.UtcNow;
DateTimeOffset nextTime = now.Date.AddDays(now.Hour < hourOfDay ? 0 : 1).AddHours(hourOfDay);
TimeSpan delay = nextTime - now;
return delay;
}
To expound the issue is coming in from this line.
This is a
DateTimeobject unbeknownst to you, you are actually doing an implicit conversion to theDateTimeOffsetobjectnextTime.This
nextTimeobject created will have anOffsetof 1 hour since "our servers(+1GMT)".So essentially time close to 5am (1 hr and less) will generate a
DateTimeOffsetobject of the current day with anOffsetof 1 hour which you compared withnow(DateTimeOffsetobject of the current day with anOffsetof 0 hours).Alternative solution:
Is to convert it back to a
DateTimeOffsetwith zeroOffsetAdditional Info
Conversions from DateTime to DateTimeOffset
An Implicit conversion is what you're doing on that line.