How to convert time between timezones (UTC to EDT)?

后端 未结 4 1108
暗喜
暗喜 2020-12-17 16:37

I need to have a common function to convert UTC time to EDT. I have a server in India. An application in it needs to use EDT time for all time purposes.

I am using

4条回答
  •  无人及你
    2020-12-17 17:12

    I would have said that you should use UTC for calculations of time periods, so that you avoid issues of daylight saving time and then use LocalTime for display only.

    DateTime.ToLocalTime for UTC to whatever the local time zone is and then DateTime.ToUniversalTime to convert from local time to UTC.

    Edit after comment 1

    Do I take it then that you're after displaying a different timezone to that of the server?

    If you're using web pages to access your server then use HttpRequest.UserLanguages to help create a CultureInfo object and use that to parse your DateTime object. Look here for a full explanation:Microsoft link on displaying local user time for web pages.

    If you're using client-server architecture then if the LocalTime call is on the client side it will display the LocalTime for the client. You then convert it to UTC to send back to your server.

    Either way your server doesn't need to know where the client is so if you have multiple clients in multiple timezones then all calculations will match. It will also allow you to show the times in any timezone that you wish by use of different Culture objects.

    Edit 2 copied my second comment

    You can get time data in UTC format from the server. Then you can convert it using DateTime.ToLocalTime or DateTime.ToUniversalTime as requried. If you're including dates as well and need to cope with say US MM/dd/yyyy and european dd/MM/yyyy formats the you can use CultureInfo class to parse the DateTime value accordingly. It sounds like more work than what you have at the moment, but it would mean that if you move your server again then you don't need to recode the DateTime handling.

    A new point

    Another point to look at is clock synchronisation between the server and the clients using NTP (Network Time Protocol) or SNTP (Simple Network Time Protocol) if it is accurate enough. I don't know what OS you are using but this is used by Windows Server time services to synchronise networks.

提交回复
热议问题