Aware this is an answer many years later, but came across this today and once I worked out my problem wanted to add some context I didn't see in other answers.
Going back to the OPs code snippet the reason it doesn't do what the OP expected of taking a UTC time string and storing it as a UTC DateTime
is because the DateTimeStyles.AssumeUniversal
only specifies that the input string is a UTC string. By default C# will create DateTime
's as a DateTimeKind.Local
. This was pointed out in another answer. This means the time is converted from UTC to Local time.
To make sure that your end result ends up being a UTC DateTime
you need to use the DateTimeStyles
of DateTimeStyles.AdjustToUniversal
. This was also mentioned in other answers. However, if your input string doesn't have an obvious timezone then it may be assumed to be local and then converted from Local to UTC.
Luckily DateTimeStyles is actually a flag enum meaning we can use both the above options at the same time. E.g:
DateTime testDate = DateTime.ParseExact("2012-08-10T00:51:14.146Z", "yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal);