views:

557

answers:

6

I am storing date/times in the database as UTC and computing them inside my application back to local time based on the specific timezone. Say for example I have the following date/time:

01/04/2010 00:00

Say it is for a country e.g. UK which observes DST (Daylight Savings Time) and at this particular time we are in daylight savings. When I convert this date to UTC and store it in the database it is actually stored as:

31/03/2010 23:00

As the date would be adjusted -1 hours for DST. This works fine when your observing DST at time of submission. However, what happens when the clock is adjusted back? When I pull that date from the database and convert it to local time that particular datetime would be seen as 31/03/2009 23:00 when in reality it was processed as 01/04/2010 00:00.

Correct me if I am wrong but isn't this a bit of a flaw when storing times as UTC?

Example of Timezone conversion

Basically what I am doing is storing the date/times of when information is being submitted to my system in order to allow users to do a range report. Here is how I am storing the date/times:

public DateTime LocalDateTime(string timeZoneId)
{
    var tzi = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
    return TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzi).ToUniversalTime().ToLocalTime(); 
}

Storing as UTC:

var localDateTime = LocalDateTime("AUS Eastern Standard Time");
WriteToDB(localDateTime.ToUniversalTime());
+7  A: 

You don't adjust the date for DST changes based on whether you're currently observing them - you adjust it based on whether DST is observed at the instant you're describing. So in the case of January, you wouldn't apply the adjustment.

There is a problem, however - some local times are ambiguous. For example, 1:30am on October 31st 2010 in the UK can either represent UTC 01:30 or UTC 02:30, because the clocks go back from 2am to 1am. You can get from any instant represented in UTC to the local time which would be displayed at that instant, but the operation isn't reversible.

Likewise it's very possible for you to have a local time which never occurs - 1:30am on March 28th 2010 didn't happen in the UK, for example - because at 1am the clocks jumped forward to 2am.

The long and the short of it is that if you're trying to represent an instant in time, you can use UTC and get an unambiguous representation. If you're trying to represent a time in a particular time zone, you'll need the time zone itself (e.g. Europe/London) and either the UTC representation of the instant or the local date and time with the offset at that particular time (to disambiguate around DST transitions). Another alternative is to only store UTC and the offset from it; that allows you to tell the local time at that instant, but it means you can't predict what the local time would be a minute later, as you don't really know the time zone. (This is what DateTimeOffset stores, basically.)

We're hoping to make this reasonably easy to handle in Noda Time, but you'll still need to be aware of it as a possibility.

EDIT:

The code you've shown is incorrect. Here's why. I've changed the structure of the code to make it easier to see, but you'll see it's performing the same calls.

var tzi = TimeZoneInfo.FindSystemTimeZoneById("AUS Eastern Standard Time");
var aussieTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzi);
var serverLocalTime = aussieTime.ToLocalTime(); 
var utcTime = serverLocalTime.ToUniversalTime();

So, let's think about right now - which is 13:38 in my local time (UTC+1, in London), 12:38 UTC, 22:39 in Sydney.

Your code will give:

aussieTime = 22:39 (correct)
serverLocalTime = 23:39 (*not* correct)
utcTime = 22:39 (*not* correct)

You should not call ToLocalTime on the result of TimeZoneInfo.ConvertTimeFromUtc - it will assume that it's being called on a UTC DateTime (unless it's actually got DateTimeKind.Local, which it won't in this case).

So if you're accurately saving 22:39 in this case, you aren't accurately saving the current time in UTC.

Jon Skeet
Sorry my question was a bit rushed! What I meant was if you convert a time using `ConvertTimeFromUtc` it automatically adjusts for DST. However, as I am storing DateTimes in the database as UTC it would remove the adjustment (if necessary). So when it came to me pulling out this date time in the future (when we are no longer in a time that observes DST) that datetime would not be re-adjusted back...if that makes sense? I think storing the offset would be the best solution then I know for sure if the date requires adjusting or not.
James
@James: No, it doesn't work like that. Whether DST is applied or not depends on the date that's being converted, not the current date. So "when we are no longer in a time that observes DST" is irrelevant.
Jon Skeet
Ah ok, so if I pull that particular date out and do the conversion it should still calculate as expected?
James
@James: Yes, if you've accurately stored it as UTC you should then be able to accurately display it in any other time zone.
Jon Skeet
@Jon, well what I am doing is **always** converting the current date/time into local time (for that particular timezone) via the `ConvertFromTimeUtc` and `ToLocalTime`. Then when I am storing it in the database I am using the `ToUniversalTime` method to convert the time into UTC.
James
@James: When you say "ToUniversalTime" and "ToLocalTime" do you mean on DateTime or DateTimeOffset?
Jon Skeet
On the DateTime
James
@James: Don't do that. In fact, don't use DateTime at all if possible. It will always convert to local/UTC based on the time zone of the machine it's running on, which probably isn't what you mean. DateTimeOffset is probably what you want to use here.
Jon Skeet
@Jon, yeah I knew it done that. However, what I am doing is calling `DateTime.UtcNow` (which as you said gives me machine local UTC) then I call `ConvertTimeFromUtc` for the specific timezone and use `ToLocalTime`. I was verifying the times using some online websites and it seemed to be inline. Is this not a valid way of doing it?
James
@James: It depends on exactly what you're trying to do... it's not terribly clear from your description. But unless you want the machine-local time zone to get involved (which you probably don't) you should *not* be using DateTime.ToLocalTime. It would be very helpful if you either started a new question or modified the existing one to show some full code, and explained *exactly* what you're trying to do with it.
Jon Skeet
I have updated my post to show you an idea to how I am doing it.
James
@Jon, I did some research right here on SO and found that what I am doing is actually the way to do it. Thanks for the heads up though with the DST stuff.
James
@James: No, what you're doing isn't right. I'll show you why in an edit.
Jon Skeet
Ok I think I was getting confused as I thought it would return the UTC time for that timezone. So it returns the local time? So there is no need to call `.ToLocalTime` at all. However, is it still correct to store `.ToUniversalTime` in the database from the converted time i.e. in this case calling `aussieTime.ToUniversalTime()`? This should give me the UTC for aussie time.
James
@jon, I reviewed my code and turns out I am actually doing `ConvertTimeFromUtc(DateTime.UtcNow, tzi).ToUniversalTime().ToLocalTime()` so I think thats why I was getting the correct result.
James
@James: In that case you're getting the *local* time on the server. All of that is equivalent to just `DateTime.Now`, basically. Again, it's still not UTC. If you're generating the time at the server anyway, why aren't you just using `DateTime.UtcNow`? Where does the Australian time come into it at all? UTC here and now is the same as UTC there and now, if you see what I mean.
Jon Skeet
@Jon, I thought I would have to convert it to Aussie time before I stored the UTC? When I convert it to aussie time then do `ToUniversalTime` that is different to doing `DateTime.UtcNow` as `DateTime.UtcNow` gives me UTC of the current server time, not the time in aussie. Or am I missing something here? You are basically saying that `DateTime.UtcNow` is the same as converting the datetime to aussie time and calling `ToUniveralTime` on that?
James
@James: I think you're missing what UTC is about, or what time zones mean. UTC is the same world-wide - that's the point of it. There's no difference between "UTC in Australia" and "UTC in the US" for example.
Jon Skeet
@Jon, so if I have a datetime (regardless of whether its been converted to a different timezone or not) how can I store the UTC equivalent of that date? Apologies for this, I am fairly new to the whole UTC stuff and how it all works.
James
@James: You need to be a bit more precise, I'm afraid. The problem with DateTime is that it can represent a UTC time, an "unspecified" time or a "local" time (where "local" is often assumed to be "local to the machine"). Where are you getting the date/time to start with? If you're constructing it, then DateTime.UtcNow will always mean "this instant, in UTC" and that should give the same value wherever you run it. (Modulo the computer's clock being inaccurate :)
Jon Skeet
@Jon: The datetimes are being extracted from a couple of places. However, the most significant ones are being extracted from emails (received datetime). So say I receive an email from australia which would be about +10 hours ahead of the current system time (as I am in the UK) is it safe to call `.ToUniveralTime()` to get the UTC time of that *instant*?
James
@James: The email should include the time zone offset, so you shouldn't need to get the time zone itself (I believe). The safest bet would be to parse it as a DateTimeOffset instead of a DateTime - that removes a lot of the ambiguity. Basically it's all pretty confusing - which is part of the reason I started Noda Time :)
Jon Skeet
James
@James: I'm hoping there'll be a first release of Noda Time some time towards the end of the year. The problem with DateTime is that it can represent a UTC time *or* a local time *or* an unspecified time... and "local" is used to mean "local to the server" rather than "local to this specific time zone". What a mess :(
Jon Skeet
@Jon, yeah it all seems a little ambiguous and you can see how people not familiar with this area (myself being proof) can get confused! Hopefully I can figure out a good workaround. Thanks for all the help.
James
@Jon posted another question, wondering if you could take a looksee. Thanks. http://stackoverflow.com/questions/2647472/safely-convert-utc-datetimes-to-local-time-based-on-tz-for-calculations
James
A: 

Correct me if I am wrong but isn't this a bit of a flaw when storing times as UTC?

Yes it is. Also, days of the adjustment will have either 23 or 25 hours so the idiom of the prior day at the same time being local time - 24 hours is wrong 2 days a year.

The fix is picking one standard and sticking with it. Storing dates as UTC and displaying as local is pretty standard. Just don't use a shortcut of doing calculations local (+- somthing) = new time and you are OK.

drewk
+1  A: 

You could work around this by also storing the particular offset used when converting to UTC. In your example, you'd store the date as something like

31/12/2009 23:00 +0100

When displaying this to the user, you can use that same offset to convert, or their current local offset, as you choose.

This approach also comes with its own problems. Time is a messy thing.

Thomas
+1 Yeah I reckon this might actually solve the issue. Means when I am computing it back I will be able to tell whether it was adjusted or not.
James
A: 

This is a huge flaw but it isn't a flaw of storing times in UTC (because that is the only reasonable thing to do -- storing local times is always a disaster). This is a flaw is the concept of daylight savings time. The real problem is that the time zone information changes. The DST rules are dynamic and historic. They time when DST starting in USA in 2010 is not the same when it started in 2000. Until recently Windows did not even contain this historic data, so it was essentially impossible to do things correctly. You had to use the tz database to get it right. Now I just googled it and it appears that .NET 3.5 and Vista (I assume Windows 2008 too) has done some improvement and the System.TimeZoneInfo actually handles historic data. Take a look at this.

But basically DST must go.

MK
+2  A: 

It's good that you are attempting to store the dates and times as UTC. It is generally best and easiest to think of UTC as the actual date and time and local times are just pseudonyms for that. And UTC is absolutely critical if you need to do any math on the date/time values to get timespans. I generally manipulate dates internally as UTC, and only convert to local time when displaying the value to the user (if it's necessary).

The bug that you are experiencing is that you are incorrectly assigning the local time zone to the date/time values. In January in the UK it is incorrect to interpret a local time as being in a Summertime time zone. You should use the time zone that was in effect at the time and location that the time value represents.

Translating the time back for display depends entirely on the requirements of the system. You could either display the times as the user's local time or as the source time for the data. But either way, Daylight Saving/Summertime adjustments should be applied appropriately for the target time zone and time.

Jeffrey L Whitledge
@Jeff, I am converting the UTC dates back based using the `ConvertTimeFromUtc` method based on the Timezone. So I am not manually trying to adjust for DST, it is the actual method that adjust automagically. I will change my date as I think its confusing folk, it was just an example.
James
+1  A: 

The TimeZoneInfo.ConvertTimeFromUtc() method will solve your problem:

using System;

class Program {
  static void Main(string[] args) {
    DateTime dt1 = new DateTime(2009, 12, 31, 23, 0, 0, DateTimeKind.Utc);
    TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
    Console.WriteLine(TimeZoneInfo.ConvertTimeFromUtc(dt1, tz));
    DateTime dt2 = new DateTime(2010, 4, 1, 23, 0, 0, DateTimeKind.Utc);
    Console.WriteLine(TimeZoneInfo.ConvertTimeFromUtc(dt2, tz));
    Console.ReadLine();
  }
}

Output:

12/31/2009 11:00:00 PM 
4/2/2010 12:00:00 AM

You'll need .NET 3.5 or better and run on an operating system that keeps historical daylight saving time changes (Vista, Win7 or Win2008).

Hans Passant
@nobugz, I am actually using that method to do the conversion. My question was just based on a theory by observing the information that is being stored in my database.
James
@James, I showed you the result of the theory. Works on my machine. Did you review the requirements at the bottom of my post? Do you get different results? That's the way to keep moving the question...
Hans Passant
@nobugz, no I hadn't test it, I was just thinking (from looking at how the date/times where being stored in the db) what would happen if I am not *currently* in a DST observing time. Would the date/time be readjusted correctly. However, as @Jon has mentioned DST is taken into consideration based on the actual datetime itself and not the current datetime. Thanks.
James