govin
govin

Reputation: 6693

Parsing an ISO string in UTC to DateTimeKind.UTC

Let's say, I have a string like this - "2014-09-30T20:38:18.280", how can I parse this into a DateTime field of DateTimeKind.Utc.

When I perform DateTime.Parse("2014-09-30T20:38:18.280"), it returns the date time in DateTimeKind.Unspecified. When I try to call ToUniversalTime() on that, it shifts the time adjusting UTC offset.

I basically want "2014-09-30T20:38:18.280" itself represented in UTC

Upvotes: 1

Views: 687

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500435

Specify DateTimeStyles.AssumeUniversal when you parse.

If no time zone is specified in the parsed string, the string is assumed to denote a UTC.

I'd also use DateTime.ParseExact and specify the invariant culture:

var time = DateTime.ParseExact(text, "yyyy-MM-dd'T'HH:mm:ss.fff",
                               CultureInfo.InvariantCulture,
                               DateTimeStyles.AssumeUniversal);

Upvotes: 5

Related Questions