C# datetime parse issue

You are parsing the UTC date but the DateTime.Kind is local. You should parse with DateTimeStyles.AdjustToUniversal to mark the Kind as Utc.

        DateTime testDate = DateTime.ParseExact("2012-08-10T00:51:14.146Z", "yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);

        Trace.WriteLine(testDate);  //  8/9/2012 8:51:14 PM
        Trace.WriteLine(testDate.ToString()); //  8/9/2012 8:51:14 PM
        Trace.WriteLine(testDate.ToUniversalTime()); //  8/10/2012 12:51:14 AM
        Trace.WriteLine(testDate.Kind); // Local

       testDate = DateTime.ParseExact("2012-08-10T00:51:14.146Z", "yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);

        Trace.WriteLine(testDate);//  8/10/2012 12:51:14 AM
        Trace.WriteLine(testDate.ToString());//  8/10/2012 12:51:14 AM
        Trace.WriteLine(testDate.ToUniversalTime());//  8/10/2012 12:51:14 AM
        Trace.WriteLine(testDate.Kind); // Utc

What is your server timezone, if you use AssumeUniversal it will convert your input time to UTC time.

You probably in EST then.


You should use DateTimeStyles.AdjustToUniversal. The input DateTime is already universal, and the AdjustToUniversal enum option will convert the input to local time though you will get a resultant Kind of DateTimeKind.Unspecified.

Tags:

C#

.Net

Datetime