Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Local Time To UTC

Tags:

c#

.net

datetime

I'm up against an issue storing datetimes as UTC and confused why this does not yield the same result when changing timezones:

var dt = DateTime.Parse("1/1/2013");
MessageBox.Show(TimeZoneInfo.ConvertTimeToUtc(dt, TimeZoneInfo.Local).ToString());

I am manually switching my local time zone on the machine between eastern and central.

Central yields 1/1/2013 6:00:00 AM, and Eastern yields 1/1/2013 5:00:00 AM. What am I missing here? They should be the same regardless of the time zone, correct?

Thanks so much in advance!

like image 288
Mark Hardin Avatar asked May 20 '13 14:05

Mark Hardin


People also ask

How do you calculate UTC time?

Examples of how to convert UTC to your local time To convert 18:00 UTC (6:00 p.m.) into your local time, subtract 6 hours, to get 12 noon CST. During daylight saving (summer) time, you would only subtract 5 hours, so 18:00 UTC would convert to 1:00 p.m CDT. Note that the U.S. uses a 12-hour format with a.m. and p.m.

What is my timezone in UTC?

Current time: 17:51:22 UTC. UTC is replaced with Z that is the zero UTC offset. UTC time in ISO-8601 is 17:51:22Z. Note that the Z letter without a space.

Is UTC always 24-hour time?

UTC time - Coordinate Universal Time Simplifying, the UTC time divides time into days, hours, minutes and seconds, but while one day is always of 24 hours and one hour always of 60 minutes, a minute, while almost always consists of 60 seconds, sometimes it can be a period of 59 or 61 seconds.


1 Answers

I think what you are missing is that the DateTime returned by your DateTime.Parse() statement doesn't come with a time zone. It's just a date and time that can be in any time zone. When you call TimeZoneInfo.ConvertTimeToUtc(dt, TimeZoneInfo.Local), you are telling it which time zone it starts in. So if you start in Central, you will get one answer, whereas if you start in Eastern, you will get an answer that is an hour earlier, UTC. Indeed, this is what your code shows.

like image 117
Katie Kilian Avatar answered Oct 14 '22 09:10

Katie Kilian