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 function doesn't work properly. I wonder if there is a solution to this. I have done some research and found two ways. First is to use GetUTCDate() function. However, I would need to do the conversion when I display the information. I am sure my web application is used for only my timezone. So I would like to avoid this. Second way, this is the closest I could get this done by using SwitchOffSet function:
CREATE TABLE [dbo].[Test_Date](
[test_id] [int] NOT NULL,
[test_date] [datetime2](7) NOT NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Test_Date] ADD CONSTRAINT [DF_Test_Date_test_date] DEFAULT (switchoffset(CONVERT([datetimeoffset],getutcdate()),'+13:00')) FOR [test_date]
GO
However, my problem is the +13:00 cause in the next few months, it will be +12:00 cause of the day light saving time change. As a result, I would need to change it every time. Anybody has a solution to this?
Thanks.
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
You can use
SYSDATETIMEOFFSET
functionMSDN description:
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.
Since Sql Server 2016 you can use
AT TIME ZONE
...... as specified in the documentation
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.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.