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

后端 未结 5 1093
不知归路
不知归路 2021-02-13 19:59

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:17

    I have had the same issue and i made the following extension methods.

        public const string UTC = "UTC";
    
       public static DateTime Convert(this DateTime date, string fromZone, string toZone)
        {
            TimeZoneInfo to = TimeZoneInfo.FindSystemTimeZoneById(toZone);
            TimeZoneInfo from = TimeZoneInfo.FindSystemTimeZoneById(fromZone);
            return new DateTime(TimeZoneInfo.ConvertTime(date, from, to).Ticks, DateTimeKind.Unspecified); 
        }
    
        public static bool IsDayLightSaving(this DateTime date, string zone)
        {
            TimeZoneInfo to = TimeZoneInfo.FindSystemTimeZoneById(zone);
            return to.IsDaylightSavingTime(date);
        }
    
        public static DateTime ConvertToUTC(this DateTime date, string fromZone)
        {
            return date.Convert(fromZone, DateTime_Extension.UTC);
        }
    
        public static DateTime ConvertToLocal(this DateTime date, string toZone)
        {
            return date.Convert(DateTime_Extension.UTC, toZone);
        }
    

    The problem I found is actually finding the current users Time Zone. As this is not passed in the Header (you can get it via JavaScript) I have decided to ask the user to select their time zones when they register

    Hope this helps

提交回复
热议问题