0

I am fetching adjustment rules for Eastern Standard Time (TimeZoneInfo.AdjustmentRule).

I get TimeZoneInfo.AdjustmentRule.DaylightDelta to know the hours or minutes that are changing but I am not finding any way to know if the time is falling backward by the delta hours or going forward.

So basically I am trying to find out if I have to add the hours or subtract the hour.

I know there is a property TimeZoneInfo.IsInvalidTime but that does not seem to me the best way to first add the hour check if it is invalid, then subtract and again check if it is now valid.

Is there any better and direct way to know this?

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
Pawan Nogariya
  • 8,330
  • 12
  • 52
  • 105

1 Answers1

1

The DaylightDelta property is the amount of time that is added to the standard offset to get the daylight offset during the period the rule applies to. In most cases it will be 1 hour, but there are exceptions so don't hardcode that.

For example, in the US Eastern time zone (using the "Eastern Standard Time" identifier on Windows, or the "America/New_York" identifier in other operating systems) the current Standard Time offset from UTC is -5 and the current Daylight Time offset is -4.

-5 + 1 = -4 

That said, you should probably not be taking the approach you describe in your question. In most cases, you will never need to access the adjustment rules yourself. Just use the conversion methods on TimeZoneInfo, such as TimeZoneInfo.ConvertTime (and others).

One major supporting reason is that there is an additional field in each adjustment rule called _baseUtcOffsetDelta that is not exposed in the public API surface. The conversion methods take it into consideration, but because it's not exposed you can't apply it yourself without resorting to reflection. (This field is used for edge cases that crop up when a time zone has historical changes to its Standard Time offset.)

If you still decide to work with the adjustment rules yourself, keep in mind that there's a huge difference between adjusting a datetime for DST and advancing a datetime by a duration. Both are performed with addition, but one takes DateTimeKind and/or offset into consideration while the other does not. If you're not very careful, you could end up representing a different point in time than you intended.

Again, in the vast majority of use cases - you do not need to use the adjustment rules yourself. Even if you need to change the behavior of ambiguous/invalid time handling, you should take an approach similar to the one I described in this other answer (using the ToDateTimeOffset extensions method posted there).

Lastly - if you are finding it difficult to work with TimeZoneInfo for your use case, you should consider using Noda Time instead. Its API is much more verbose, but that may guide you to better outcomes.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575