Storing DateTime (UTC) vs. storing DateTimeOffset - sql

I usually have an "interceptor" that right before reading/writing from/to the database does DateTime conversion (from UTC to local time, and from local time to UTC), so I can use DateTime.Now (derivations and comparisions) throughout the system without worrying about time zones.
Regarding serialization and moving data between computers, there is no need to bother, as the datetime is always UTC.
Should I continue storing my dates (SQL 2008 - datetime) in UTC format or should I instead store it using DateTimeOffset (SQL 2008 - datetimeoffset)?
UTC Dates in the database (datetime type) have been working and known for so long, why change it? What are the advantages?
I have already looked into articles like this one, but I'm not 100% convinced though. Any thoughts?

There is one huge difference, where you cannot use UTC alone.
If you have a scenario like this
One server and several clients (all geographically in different timezones)
Clients create some data with datetime information
Clients store it all on central server
Then:
datetimeoffset stores Local time of the client and ALSO offset to the UTC time
all clients know UTC time of all data and also a local time in the place where the information originated
But:
UTC datetime stores just UTC datetime, so you do not have information about local time in the client location where data originated
Other clients do not know the local time of the place, where datetime information came from
Other clients can only calculate their local time from the database (using UTC time) not the local time of the client, where the data originated
Simple example is flight ticket reservation system ... Flight ticket should contain 2 times:
- "take off" time (in timezone of "From" city)
- "landing" time (in timezone of "Destination" city)

You are absolutely correct to use UTC for all historical times (i.e. recording events happened). It is always possible to go from UTC to local time but not always the other way about.
When to use local time? Answer this question:
If the government suddenly decide to change daylight savings, would you like this
data to change with it?
Only store local time if the answer is "yes". Obviously that will only be for future dates, and usually only for dates that affect people in some way.
Why store a time zone/offset?
Firstly, if you want to record what the offset was for the user who carried out the action, you would probably be best just doing that, i.e. at login record the location and timezone for that user.
Secondly if you want to convert for display, you need to have a table of all local time offset transitions for that timezone, simply knowing the current offset is not enough, because if you are showing a date/time from six months ago the offset will be different.

A DATETIMEOFFSET gives you the ability to store local time and UTC time in one field.
This allows for very simple and efficient reporting in local or UTC time without the need to process the data for display in any way.
These are the two most common requirements - local time for local reports and UTC time for group reports.
The local time is stored in the DATETIME portion of the DATETIMEOFFSET and the OFFSET from UTC is stored in the OFFSET portion, thus conversion is simple and, since it requires no knowledge of the timezone the data came from, can all be done at database level.
If you don't require times down to milliseconds, e.g. just to minutes or seconds, you can use DATETIMEOFFSET(0). The DATETIMEOFFSET field will then only require 8 bytes of storage - the same as a DATETIME.
Using a DATETIMEOFFSET rather than a UTC DATETIME therefore gives more flexibility, efficiency and simplicity for reporting.

Related

Datetime Offset Conversion in SQL

I’m working with a table that uses date time offset. I have a value that looks like 2020-01-02 13:30:00 -07:00.
Is the time in my time zone 13:30 or do I need to subtract 7 hours from it. I saw people do it differently on YouTube.
In MS SQLServer, the last section of the string representation that you posted of the DateTimeOffset describes the time zone. So, if you are currently located in time zone -7:00 (e.g., Arizona, USA), then the time portion of the string refers to your local time, not UTC. See the Microsoft documentation:
For example, 1999-12-12 12:30:30.12345 -07:00 should be represented [in UTC] as
1999-12-12 19:30:30.12345Z
Someone would subtract the offset from the number only if they want to manually get the UTC value, but that would might produce errors if the data come from a daylight saving time (DST) region, so you would need to enforce DST handling at the time of entry. SQLServer already stores the data in UTC behind the scenes:
The data is stored in the database and processed, compared, sorted,
and indexed in the server as in UTC.

Daylight savings time and UTC time

We use a program that saves the time-stamps in UTC time. We are a local to Utah company so we are affected by Daylight Savings time.
For example if we receive a call right now it is 12:52:00 MST and it would be saved in the database as 19:52:00.
My first concern is next year when DST starts again on March 13th 2016 and I run this at the exact same time. Will the time stamp in UTC be then 18:52:00 or would it stay at 19:52:00?
My second concern is if I convert the date in the database to my local time so I have to first check if it DST and then if it is take the time -6 and if not it would be -7?
So using the above example:
IsDST = 01:52:00 (-6)
IsNotDST = 12:52:00 (-7)
I assume this is something I need to worry about having to convert to/from UTC?
My main question aside from the two concerns above. Is there anything built into SQL Server/T-SQL that handles this conversion for me or do I need to write everything myself to take care of the need?
I have it started already, but now need to work in the DST if it is necessary
DECLARE #declared_start_datetime DATETIME,
#declared_end_datetime DATETIME,
#converted_start_datetime DATETIME,
#converted_end_datetime DATETIME
SET #declared_start_datetime = '11/04/2015 07:00:00' -- Hour we open phones
SET #declared_end_datetime = '11/04/2015 18:00:00' -- Hour we close phones
SET #converted_start_datetime = DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), #declared_start_datetime)
SET #converted_end_datetime = DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), #declared_end_datetime)
select #declared_start_datetime as 'Declared Start',
#declared_end_datetime as 'Declared End'
select #converted_start_datetime as 'Converted Start',
#converted_end_datetime as 'Converted End'
For example if we receive a call right now it is 12:52:00 MST and it would be saved in the database as 19:52:00.
My first concern is next year when DST starts again on March 13th 2016 and I run this at the exact same time. Will the time stamp in UTC be then 18:52:00 or would it stay at 19:52:00?
Mountain Standard Time is UTC-7, and US Mountain Daylight time is UTC-6. It's a lot easier to reason about if you write out the full date, time, and offset(s) involved in the conversion. Here it is in standard ISO8601 extended format:
2015-11-06T12:52:00-07:00 = 2015-11-06T19:52:00Z
2016-03-13T12:52:00-06:00 = 2016-03-13T18:52:00Z
Each local time on the left side of the equation is marked with the correct local time and local offset for that time. Then to get to UTC (identified by Z), you simply subtract the offset from the local time. Or, think of it as inverting the sign and adding, if that's easier to rationalize.
So yes, it would store it at 18:52:00 UTC when you are in daylight time. This is the correct behavior.
My second concern is if I convert the date in the database to my local time so I have to first check if it DST and then if it is take the time -6 and if not it would be -7?
Yes, but keep in mind that it's the date and time reflected by the timestamp you're converting. It makes no difference whether you are currently in DST or not.
However, keep in mind that time zone conversion should usually be avoided in the database layer, if you can all help it. In the vast majority of use cases, it's an application layer concern.
For example, if you're writing to SQL Server from an application built in .NET, then you could use the TimeZoneInfo class with the "Mountain Standard Time" ID (which is for both MST and MDT). Or, you could use the Noda Time library with the TZDB identifier of "America/Denver".
By using a library, you don't have to concern yourself with all of the various details of when DST starts and stops, nor how it has changed throughout history in different parts of the world.
In the rarer case where you actually need time zone conversion done at the database level, you can certainly write a stored procedure or UDF of your own (such as some of the question comments linked to), but depending on your needs they may not be sufficient. Typically they tend to encode just one set of fixed rules for time zone conversions, so they won't take other time zones or historical changes into account.
There are a few generic time zone solutions for SQL Server, but unlike other database platforms, there's nothing built in. I'll recommend my SQL Server Time Zone Support OSS project, and there are others if you search. But really, you should hopefully not need this, and should do the conversion in the application layer whenever possible.
Update: With SQL Server 2016 CTP 3.1, there is now built-in support for time zones via the AT TIME ZONE statement. See the CTP announcement for examples.

Time difference issue in two different countries

There are two clients with same window application. One is in India and other one is in Belgium. Sql server and web service application is hosted at Belgium. In sql I am storing UTC date time.
Now issue is a time difference for this two clients. I want to show UTC time in history form that mean what is stored in Database I have to bind that data to gird. No any extra code because I suppose to bind UTC date-time. Event then I get time difference for this two client.
Blue header screen is of a Indian client and other one is of a Belgium client. In Belgium time is showing exactly as in Database but difference is for India. Am I missing anything in configuration or what?
You have to convert both time zone in standard UTC and save it. Used dateadd() function to manipulate datetime. such as
declare #IST_date datetime
declare #BE_date datetime
declare #UTC_date datetime
--Indian standard time is (GMT + 5:30 hrs)
-- Belgium standard time is ( GMT + 1 hour)
select #UTC_date = DATEADD(hh,5.30, #IST_date)
select #UTC_date = DATEADD(hh,1, #BE_date)
why not simply convert the value at display ?
DateTime MyDate = Data["ChangedDate"];
DateTime MyDateUTC = MyDate.ToUniversalTime();
tadaaaaa
Ditch System.DateTime and use Noda Time!
Getting Started with Noda Time
System.DateTime uses the system culture and time zone at unpredictable moments, where Noda Time works without any defaults. Takes a bit of work to understand, but you'll never look back.
Use Noda time on the client, and store all the values in UTC in the database. You may also wish to store the original time zone that the date time was entered in.

Which SQL datatype should I use to store datetime from GPS devices?

I'm working on a project where I have to gather data from GPS devices located in different countries (timezones + daylight savings) and display those data to different users also from different countries. I'm thinking about saving the date in UTC format (that is what I receive from the GPS device) but then again I belive I'll have trouble converting that date to the user's local date (I have to display historical data also so I'll have to account for daylight savings for the given date). Maybe the datetimeoffset datatype would be more appropriate but how would I go about converting the received UTC date to the datetimeoffset datatype? What would you suggest? Thanks!
As you don't have to store any time zone along with the datetime, you can store them as UTC. That has the advantage of being linear, and easy to document. You don't have to bother with gaps and overlaps at the daylight savings time switches.
Convert the date to the local time zone when you display it to the user. It doesn't make sense to convert it to a local time zone until you know which user will be viewing the data.

Oracle Date field - Time issues

We have two databases, in two separate locations. One of the databases resides in a separate time zone than our users.
The problem is that when the database that is located in a separate time zone is updated, with a Date value, the database automatically subtracts 1:00 hour from the Date it was passed.
The issue is that, when passing a NULL date (12:00:00), the DAY value is changed to a previous day.
The updates are done via stored procedures, and the front end is a VB.NET smartclient.
How would you handle this the proper way? I basically don't even want to store the TIME at all, but I can't seem to figure out how to do that.
Not clear on what datetime you want in the database, or what the application is passing.
Assume the user's PC is telling him it is Tuesday, 12:30am, and the clock on the Db server is saying Monday, 11:30pm.
If you insert a value for the 'current date' (eg TRUNC(SYSDATE)) then, as far as the database is concerned, it is still Monday.
If you insert a value for the 'current time (eg SYSDATE), it is also still Monday.
if you insert a value for the session's current time (eg CURRENT_TIMESTAMP) and timezone and ask the database to store it in the database, it will store 11:30pm.
If you ask the database to store the datetime '2009-12-31 14:00:00', then that is what it will store. If you ask it to store the datetime/timezone '2009-12-31 14:00:00 +08:00', then you are in the advanced manual. You can ask the database to store timestamps with timezone data. Also consider daylight saving
I would investigate using the TRUNC function in your stored proc method that updates the table. If the data type in the method (that updates the table) is not a DATE type then use the to_date function in conjunction with the TRUNC function.
This is outside of the scope of the question you are asking, but I would recommend in ALL cases where users are accessing a database from different time zones, the server and database clocks time zone should be set to UTC. It is probably too late for that, but setting the datbase server to UTC eliminates the problems caused by daylight savings time and different time zones.
In my opionion, Date/Time data can and should always be stored in UTC. This data can be converted to local time at the point where it is presented to the user. Oracle actually makes this easy with the TIMESTAMP with TIME ZONE data type. It allows you to access the data either as UTC (SYS_EXTRACT_UTC) or local time (Local to the database server.)
It is never the same day all places in the world, so dates cannot be considered without time.
Of course another of my opinions is that Daylight Savings time should be eliminated. But that is another topic.