Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does DateTime.ToUniversalTime() work?

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?

like image 210
derGral Avatar asked Jul 29 '09 16:07

derGral


People also ask

What is ToUniversalTime in C#?

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.

How do I get current UTC time in C#?

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 ();

What is UTC format DateTime?

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.

How do I use DateTime UtcNow?

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.


1 Answers

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.

like image 94
womp Avatar answered Sep 18 '22 19:09

womp