How to elegantly deal with timezones

后端 未结 7 529
庸人自扰
庸人自扰 2020-11-28 17:31

I have a website that is hosted in a different timezone than the users using the application. In addition to this, users can have a specific timezone. I was wondering how ot

7条回答
  •  Happy的楠姐
    2020-11-28 18:23

    After several feedbacks, here is my final solution which I think is clean and simple and covers daylight saving issues.

    1 - We handle the conversion at model level. So, in the Model class, we write:

        public class Quote
        {
            ...
            public DateTime DateCreated
            {
                get { return CRM.Global.ToLocalTime(_DateCreated); }
                set { _DateCreated = value.ToUniversalTime(); }
            }
            private DateTime _DateCreated { get; set; }
            ...
        }
    

    2 - In a global helper we make our custom function "ToLocalTime":

        public static DateTime ToLocalTime(DateTime utcDate)
        {
            var localTimeZoneId = "China Standard Time";
            var localTimeZone = TimeZoneInfo.FindSystemTimeZoneById(localTimeZoneId);
            var localTime = TimeZoneInfo.ConvertTimeFromUtc(utcDate, localTimeZone);
            return localTime;
        }
    

    3 - We can improve this further, by saving the timezone id in each User profile so we can retrieve from the user class instead of using constant "China Standard Time":

    public class Contact
    {
        ...
        public string TimeZone { get; set; }
        ...
    }
    

    4 - Here we can get the list of timezone to show to user to select from a dropdownbox:

    public class ListHelper
    {
        public IEnumerable GetTimeZoneList()
        {
            var list = from tz in TimeZoneInfo.GetSystemTimeZones()
                       select new SelectListItem { Value = tz.Id, Text = tz.DisplayName };
    
            return list;
        }
    }
    

    So, now at 9:25 AM in China, Website hosted in USA, date saved in UTC at database, here is the final result:

    5/9/2013 6:25:58 PM (Server - in USA) 
    5/10/2013 1:25:58 AM (Database - Converted UTC)
    5/10/2013 9:25:58 AM (Local - in China)
    

    EDIT

    Thanks to Matt Johnson for pointing out the weak parts of original solution, and sorry for deleting original post, but got issues getting right code display format... turned out the editor has problems mixing "bullets" with "pre code", so I removed the bulles and it was ok.

提交回复
热议问题