1

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

govin
  • 6,445
  • 5
  • 43
  • 56
  • possible duplicate of [C# datetime parse issue](http://stackoverflow.com/questions/12787368/c-sharp-datetime-parse-issue) – Steve Sep 30 '14 at 22:15

1 Answers1

5

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);
Habib
  • 219,104
  • 29
  • 407
  • 436
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194