C # parsing problem

When I try to convert the date / time from a string to DateTime, I do not get the correct value.

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

And my result is 2012-08-09 8:51:14 PM. Why is this offset? I just want this to be the same meaning.

+8
c # datetime
source share
4 answers

You are parsing a UTC date, but DateTime.Kind is local. You should parse DateTimeStyles.AdjustToUniversal to mark 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 
+18
source share

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

You are probably in est.

+3
source share

You should use DateTimeStyles.AdjustToUniversal . DateTime input is already universal, and the AdjustToUniversal drag-and-drop option converts the input to local time, although you will get the resulting DateTimeKind.Unspecified view.

+3
source share

I suggest just using .AssumeLocal instead of .AssumeUniversal .

You have a timestamp with an unknown timezone, and if you know that the timestamp refers to an event that occurred in your local timezone, then you should tell the syntax to assume that the timestamp is local to you (i.e. in your time zone).

Using .AssumeUniversal , you instruct the parser to process the timestamp as if it were a UTC timestamp, which when you display it using the local time zone, will automatically compensate for this amount.

Edit:

One important thing: The capital ā€œZā€ at the time stamp indicates that it is a UTC time stamp, which means that you want to treat it as Universal. If you want to treat it as a local timestamp, you must remove Z from the timestamp and the corresponding parsing line.

Link: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#KSpecifier

+2
source share

All Articles