SQL Server How to persist and use a time across different time zones

后端 未结 3 1221
不知归路
不知归路 2021-01-14 22:22

In SQL Server I would like to create a table to save time of an event, and would like to convert it into the timezone of the users choice for display purposes. Let us say th

相关标签:
3条回答
  • 2021-01-14 23:03

    In SQL Server 2008, use the DATETIMEOFFSET data type which is a DATETIME plus a timezone offset included.

    SELECT CAST('2010-11-23 16:35:29+09:00' AS datetimeoffset) 
    

    would be Nov 23, 2010, 4:35pm in a +9 hour (from GMT) timezone.

    SQL Server 2008 also contains functions and SQL commands to convert DATETIMEOFFSET values from one timezone to another:

    SELECT 
    SWITCHOFFSET(CAST('2010-11-23 16:35:29+09:00' AS datetimeoffset), '+01:00')
    

    would result in:

    2010-11-23 08:35:29.0000000 +01:00
    

    Same time, different timezone (+1 hour from GMT)

    0 讨论(0)
  • 2021-01-14 23:14
    1. When you save the data, save the GMT, not the local time for the user (in c# this is DateTime.UtcNow)
    2. In your application logic, record the user's timezone, and translate the GMT time to the user's local time using the timezone offset, at runtime.
    0 讨论(0)
  • 2021-01-14 23:16

    The way I've solved a similar problem is to do the following:

    1. The table design is to only store GMT time.
    2. All input goes through a stored proc that requires an input of a timezone offset.
    3. The data request is to a Table-Valued Function, with an input for the timezone offset.
    0 讨论(0)
提交回复
热议问题