.NET Framework 4.5.2 - Parsing UTC DateTime with DateTime.ParseExact()

When you parse DateTime, the DateTime className automatically converts the parsed DateTime to Locale. For example:

For parsing a UTC datetime string in O format into a DateTime object with ParseExact you have to do this:

DateTime.ParseExact("UTC_dt_string_O_format", "O", CultureInfo.InvariantCulture).ToUniversalTime();

Or, alternatively, you can do this:

DateTime.ParseExact("UTC_dt_string_O_format", "O", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);

If you use a custom format for the dates, like yyyy-MM-dd_HH:mm:ss, things are a bit different. In this case we have to use the second approach introduced before:

DateTime.ParseExact("UTC_dt_string_custom_format", "custom_format", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);

Pay attention: if you only use DateTimeStyles.AssumeUniversal you don't obtain the date with UTC TimeZone. You must use the result of the or between DateTimeStyles.AssumeUniversal and DateTimeStyles.AdjustToUniversal.

Links