How to convert a date to UTC properly and then convert it back?

后端 未结 5 2054
心在旅途
心在旅途 2021-02-13 19:48

I\'m struggling with converting DateTime to UTC, the concept and all, something I\'m not understanding correctly.

When I get a date time string, say \"7/10/2013\", I si

5条回答
  •  无人及你
    2021-02-13 20:28

    You convert back to local time using ToLocalTime(). It will see that the date/time is in July, so with DST, and hence it will shift by 4 hours and not by 5.

    If you have a client (e.g. Web browser) connecting to the server you will ultimately want the date/time converted to the local time of the client, not of the server. To do this the best way is to use TimeZone.ToLocalTime(): send to the served the time-zone the client is in and then convert directly to that time-zone all the time.

    NEVER add/subtract hours - always go through the time zone and use TimeZoone.ToLocalTime(). Adding/subtracting hours won't work when DST is involved.

    Note that it is not possible to get the current (local) time-zone from inside a browser. If your client is a browser you need to get the time-zone from some sort of configuration or have the user enter it.

    Note also that once you start to handle different time zones you no longer have just dates - you always have to deal with complete date-times: if you strip or loose the time part all the conversions won't work any more.

    Concerning question 2: UTC time is universal, not based on any specific time zone, hence once you convert to UTC you don't have to worry any more about the time-zone of the servers.

提交回复
热议问题