How does the conversion to UTC from the standard DateTime
format work?
More specifically, if I create a DateTime
object in one time zone and then switch to another time zone and run ToUniversalTime()
on it, how does it know the conversion was done correctly and that the time is still accurately represented?
The ToUniversalTime method converts a DateTime value from local time to UTC. To convert the time in a non-local time zone to UTC, use the TimeZoneInfo.
ToUniversalTime() Method in C# This method is used to convert the value of the current DateTime object to Coordinated Universal Time (UTC). Syntax: public DateTime ToUniversalTime ();
Times are expressed in UTC (Coordinated Universal Time), with a special UTC designator ("Z"). Times are expressed in local time, together with a time zone offset in hours and minutes. A time zone offset of "+hh:mm" indicates that the date/time uses a local time zone which is "hh" hours and "mm" minutes ahead of UTC.
An alternative to using UtcNow is DateTimeOffset. UtcNow. While the former indicates that a date and time value is Coordinated Universal Time (UTC) by assigning DateTimeKind. Utc to its Kind property, the latter assigns the date and time value the UTC time's offset (equal to TimeSpan.
There is no implicit timezone attached to a DateTime
object. If you run ToUniversalTime()
on it, it uses the timezone of the context that the code is running in.
For example, if I create a DateTime
from the epoch of 1/1/1970, it gives me the same DateTime
object no matter where in the world I am.
If I run ToUniversalTime()
on it when I'm running the code in Greenwich, then I get the same time. If I do it while I live in Vancouver, then I get an offset DateTime
object of -8 hours.
This is why it's important to store time related information in your database as UTC times when you need to do any kind of date conversion or localization. Consider if your codebase got moved to a server facility in another timezone ;)
Edit: note from Joel's answer - DateTime
objects by default are typed as DateTimeKind.Local
. If you parse a date and set it as DateTimeKind.Utc
, then ToUniversalTime()
performs no conversion.
And here's an article on "Best Practices Coding with Date Times", and an article on Converting DateTimes with .Net.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With