Getdate() function to get date for my timezone

后端 未结 5 1049
执念已碎
执念已碎 2021-01-05 05:49

I would love to insert a default value into a column with data type datetime2(7). However, because my website is hosted on a server in a different timezone, the getdate func

相关标签:
5条回答
  • 2021-01-05 05:50

    Since Sql Server 2016 you can use AT TIME ZONE...

    SELECT CONVERT(datetime2(0), '2015-03-29T01:01:00', 126)     
    AT TIME ZONE 'Central European Standard Time';  
    

    ... as specified in the documentation

    0 讨论(0)
  • 2021-01-05 05:53

    since the db timezone info is different with your web server, its best you explicitly pass your desired datetime value from your web app to the db, instead of using db server-side default function.

    0 讨论(0)
  • 2021-01-05 06:09

    Just store the data in UTC, and use a calendar table to calculate offsets when you read the data (see these tips: part 1, part 2, part 3). Related:

    GET UTC Date of a past date

    Daylight saving time and time zone best practices

    Best Practices working with Datetimeoffset

    how to convert all datetime columns in a sql server 2005 express database with data to UTC

    Where to set a UTC datetime value in n-tier application: Presentation Layer, Domain, or Database?

    How do I handle the timezones for every Chat message

    0 讨论(0)
  • 2021-01-05 06:14
    SELECT GETDATE() AT TIME ZONE 'UTC' AT TIME ZONE 'Central Standard Time'
    

    You need the first 'AT TIME ZONE UTC' in order to tell the DB what the value currently is in, so it knows how to get to the second given time zone, 'Central Standard Time' in my example.

    0 讨论(0)
  • 2021-01-05 06:16

    You can use SYSDATETIMEOFFSET function

    select SYSDATETIMEOFFSET()
    

    MSDN description:

    Returns a datetimeoffset(7) value that contains the date and time of the computer on which the instance of SQL Server is running. The time zone offset is included.

    More on MSDN.


    Based on clarification in the comment below:

    Because you want to store the local time of the client, SQL Server has no way of knowing what is your local time. The best option that would work best would be to send the current time from the client each time.

    0 讨论(0)
提交回复
热议问题