Johannes Schacht
Johannes Schacht

Reputation: 1334

Why are two hours added to my time

I'm struggling with time parsing. My input is a time string ending in "Z". I would expect that to be UTC. When I parse that string two hours are added to the result. I do not know why. Using a specific culture does not make any difference.

System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-US");
string inTime = "2015-04-25T23:39:15Z";
DateTime outTime = DateTime.Parse(inTime, ci);
string outTime_string = outTime.ToString("yyyy-MM-ddTHH:mm:ssZ", ci);
// outTme and outTime_string are both 2015-04-26T01:39:15Z

Upvotes: 1

Views: 172

Answers (2)

It returns local time. This will fix that:

var x = DateTime.Parse(inTime, ci, 
            System.Globalization.DateTimeStyles.AdjustToUniversal);

See this answer as well:

I would suggest you parse to a DateTimeOffset instead of a DateTime, as recommended in MSDN when using a time zone offset specifier in the format string:

Time zones are a real pain to deal with.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500785

By default, DateTime.Parse converts to a "kind" of Local. (Print out outTime.Kind to verify that.) So it understands that the source is universal - but it's adjusting it to system local time. Note that culture has nothing to do with time zone - only format and calendar system.

You can prevent that by specifying a DateTimeStyles values:

DateTime outTime = DateTime.Parse(inTime, ci, DateTimeStyles.AdjustToUniversal);

At that point, outTime.Kind will be Utc, and the value will be 23:39pm as expected.

Quick plug: the whole DateTime.Kind bit is a mess. It's awful to have a type that represents three different kinds of value. You may want to look at my Noda Time project for an alternate approach to date/time handling in .NET.

Upvotes: 7

Related Questions