I know this isn't the first time this topic has been brought up even in the past 24 hours, but I'm surprised that I have not come across one clear / best practices solution to this problem. The problem also seems to contradict what I thought was a no-brainer design decision to save all dates in UTC. I'll try to state the problem here:
Given two DateTime objects, find the duration between them while accounting for daylight savings.
Consider the following scenarios:
UtcDate - LocalDate where LocalDate is 1 millisecond earlier than a DST switchover.
LocalDateA - LocalDateB where LocalDateB is 1 millisecond earlier than a DST switchover.
UtcDate - LocalDate.ToUtc() provides a duration that did not consider the DST switch. LocalDateA.ToUtc() - LocalDateB.ToUtc() is correct, but LocalDateA - LocalDateB also disregards DST.
Now, there obviously are solutions to this problem. The solution that I'm using now is this extension method:
public static TimeSpan Subtract(this DateTime minuend, TimeZoneInfo minuendTimeZone,
DateTime subtrahend, TimeZoneInfo subtrahendTimeZone)
{
return TimeZoneInfo.ConvertTimeToUtc(DateTime.SpecifyKind(minuend,
DateTimeKind.Unspecified), minuendTimeZone)
.Subtract(TimeZoneInfo.ConvertTimeToUtc(DateTime.SpecifyKind(subtrahend,
DateTimeKind.Unspecified), subtrahendTimeZone));
}
It works, I guess. I have some problems with it though:
If dates are all converted to UTC before being saved, then this method won't help. The timezone information (and any handling of DST) is lost. I've been conditioned to always save dates in UTC, is the issue of DST just not impactful enough to make that a bad decision?
It's unlikely that someone will be aware of this method, or even thinking about this problem, when calculating the difference between dates. Is there a safer solution?
If we all work together, maybe the tech industry can convince congress to abolish daylight savings.