.NET converting datetime to UTC given the timezone

前端 未结 3 1710
南旧
南旧 2021-01-17 11:25

Using C#, I need to convert incoming datetime values into UTC. I know there is functionality in .NET for these conversions but all I have to identify the timezone is the sta

相关标签:
3条回答
  • 2021-01-17 12:05

    There is a lot of information on MSDN about converting to different time zones.

    • DateTime (MSDN), specifically look at 'DateTime Operations'.
    • TimeZoneInfo

    You probably want to use ConvertTimeBySystemTimeZoneId method (follow link for examples).

    0 讨论(0)
  • 2021-01-17 12:05

    DateTime.ToUniversalTime Method

    Or

    DateTime.UtcNow Property

    0 讨论(0)
  • 2021-01-17 12:26

    I've done it before by storing the timezone id in the database using a mapping table. i.e. A table containing the results of TimeZone.GetSystemTimeZones()

    You don't actually need to use TimeZoneInfo.FindSystemTimeZoneById() though: you can do the conversion using one of the overloads of TimeZoneInfo.ConvertTimeBySystemTimeZoneId(). This method has some overloads which take DateTime values, and some that take DateTimeOffset values (which are preferable as they specify an unambiguous point in time).

    e.g.

    TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.Now, "New Zealand Standard Time", "UTC")
    

    The real benefit of using the system time zone id rather than an offset stored in the database is that daylight savings time is automatically handled for you by TimeZoneInfo.ConvertTimeBySystemTimeZoneId.

    0 讨论(0)
提交回复
热议问题