Search code examples
c#utctimezone-offset

Determining the time zone offset of UTC time in .Net


The back-end is C# and SQL Server.

I save logging activity date times from different time zones in UTC in my DB. I need to populate a globally distributed front end so it localizes the logged UTC time based on where the front end is located, which will be known e.g. PT, ET. It also needs to handle daylight savings time which is where I'm running into difficulty.

As the UTC offset changes based on the time of the year because of daylight savings time, is there a way for me to find out what the UTC offset is in C# given that I know the date/time and the time zone.


Solution

  • is there a way for me to find out what the UTC offset is in C# given that I know the date/time and the time zone

    Technically you shouldn't need to find out this information, the underlying system clock/calendar/what-have-you should take care of it. (I'm sure anybody who has worked on date-time logic will attest to the fact that it is non-trivial to say the least.)

    Ideally, any time you need to convert a time zone, you have three things:

    1. A DateTime object representing the value to be converted.
    2. A TimeZoneInfo object representing the known current format of the DateTime object (in this case UTC).
    3. A TimeZoneInfo object representing the target time zone.

    Given those things, any time you want to display the DateTime to a localized user, you'd use something like TimeZoneInfo.ConvertTime to perform the conversion. This should ideally be done as close to the UI as possible so that backing logic is always consistently performed in UTC.