Mark Hardin
Mark Hardin

Reputation: 557

Converting Local Time To UTC

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!

Upvotes: 28

Views: 65533

Answers (5)

AD.Net
AD.Net

Reputation: 13399

There is a .ToUniversalTime() method for DateTime class

Upvotes: 13

pintu sharma
pintu sharma

Reputation: 169

When you have trouble with converting to local time to UTC then just remove the last keyword of index and then convert to UtcDateTime

NewsDate = DateTimeOffset.Parse(data.NewsDate.Remove(data.NewsDate.LastIndexOf("IST"))).UtcDateTime;

Upvotes: -1

Yanga
Yanga

Reputation: 3012

You can use NodaTime :

static string LocalTimeToUTC(string timeZone, string localDateTime)
{
    var pattern = LocalDateTimePattern.CreateWithInvariantCulture("dd/MM/yyyy HH:mm:ss");
    LocalDateTime ldt = pattern.Parse(localDateTime).Value;
    ZonedDateTime zdt = ldt.InZoneLeniently(DateTimeZoneProviders.Tzdb[timeZone]);
    Instant instant = zdt.ToInstant();
    ZonedDateTime utc = instant.InUtc();
    string output = utc.ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

    return output;
}

Upvotes: 0

paparazzo
paparazzo

Reputation: 45096

This is midnight

var dt = DateTime.Parse("1/1/2013");

Midnight in eastern and central is not the same absolute time.
That is the whole purpose of time zones.

Upvotes: 2

Katie Kilian
Katie Kilian

Reputation: 6995

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.

Upvotes: 31

Related Questions