Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to store timezone information in my DB?

Tags:

I have a asp.net-mvc web site that i took over and there is a page page where people enter information and times (including local timezone). The database is persisting a start time, an end time and a timezone as it feels a bit flaky to me. here is the code to get the list to choose from:

  static private IEnumerable<SelectListItem> GetTimeZones(string selected)     {         var timeZoneNames = TimeZoneInfo.GetSystemTimeZones()             .Where(tz => tz.DisplayName.Contains("London")                          || tz.DisplayName.Contains("Hong Kong")                          || tz.DisplayName.Contains("Mumbai")                          || tz.DisplayName.Contains("Eastern Time"))             .ConvertAll(tz => tz.DisplayName).ToList();          var items = new List<SelectListItem>();         foreach (var item in timeZoneNames)         {             var slItem = new SelectListItem();             slItem.Text = item;             slItem.Value = item;             slItem.Selected = item == selected;             items.Add(slItem);         }          return items;     } 

So its simply storing the full string that is returned from TimeZoneInfo.GetSystemTimeZones()

Are there any flaws with this approach? I am a bit concerned reading here that this comes locally from the machine as what if different machines have different settings. Also, trying to figure out if everything is listed as UTC or GMT, etc . . Any better suggestions? For example, should i do the conversion to UTC on the website and normalize all of the times in the database?

like image 590
leora Avatar asked Jul 20 '12 13:07

leora


People also ask

Does SQL Server store timezone?

How to Convert UTC to Local Time Zone in SQL Server in SQL Server. SQL Server does not store time zone data when storing timestamps. It uses the host server time as the basis for generating the output of getdate() .

How do I show time zones in SQL?

For SQL Managed Instance, return value is based on the time zone of the instance itself assigned during instance creation, not the time zone of the underlying operating system. For SQL Database, the time zone is always set to UTC and CURRENT_TIMEZONE returns the name of the UTC time zone.


1 Answers

You should store the ID returned by TimeZoneInfo.Id. That's the identifier - the string which is meant to identify the time zone. Using the display name is a really bad idea, as that can vary by culture and is less likely to be stable.

You can then use TimeZoneInfo.FindSystemTimeZoneById to retrieve the zone from the ID.

Admittedly I prefer TZDB for time zone handling, but that's a different matter :)

like image 60
Jon Skeet Avatar answered Oct 21 '22 17:10

Jon Skeet