Search code examples
.netdatetimetimezoneutc

What is the difference between DateTime.ToUniversalTime and TimeZoneInfo.ConvertTimeToUtc


I'm just starting to think properly about rolling out a webapp that will need to do things to users at the start of their day, say 6am. Also at the end of their days.

Everywhere I've been reading about people saying a lot just to use .ToUniversalTime to store the time in UTC, but when I tried this (as I suspected) it didn't work, and it just moved the time about by an hour (I'm in the UK, so I thought this was to do with some offset from GMT to UTC, although that doesn't make sense to me, as day light saving should be off at the moment).

I have a field in the db that stores the users timezone, and so when I started using ConvertTimeToUtc and fromUtc , it started doing what I was expecting it to do. Although again I'm not sure if I have to build in some logic myself to do daylight saving conversions, or it should do it for me.

I am mainly wondering why everyone was talking about .ToUniversalTime, as it really didn't seem to help me, and I couldn't understand how it could possibly know how much to offset the time to shift it to UTC, whereas the second way made sense.

Could someone explain how each methods could be useful?


Solution

  • If you run the code on a machine in a different timezone, are your calculations still going to work? This is the reason people store and treat all DateTimes as UTC - it removes any ambiguity. You wouldn't need to store the user's timezone. Any machine, anywhere, can pull a date from the database and convert it to and from local times with ease.

    If you're storing times in some other timezone, then you have to pull it out, calculate the offset to the desired timezone, including factoring in daylight savings times and international dateline considerations. In your case, you're also storing extra unnecessary information.