I have a string in the following format:
yyyy-mm-ddThh:mm:ssZ
Example string:
2013-09-15T00:24:26.4215967Z
I need to convert this in to a date time, so I use the following code:
string testDateExample = "2013-09-15T00:24:26.4215967Z";
DateTime dateConversion = XmlConvert.ToDateTime(testDateExample);
Console.WriteLine(dateConversion);
Which will output:
9/15/2013 10:24:26 AM
Why is the 00 in the time being converted to 10 am?
Why is the 00 in the time being converted to 10 am?
XmlConvert.ToDateTime(string)
returns a DateTime
with a Kind
of Local
- in other words, it's converting the UTC value to the equivalent system local time. Presumably you're in a time zone which is in UTC+10 at the moment.
You'd be better off using XmlConvert.ToDateTimeOffset
, or using the overload which also takes an XmlDateTimeSerializationMode
:
string testDateExample = "2013-09-15T00:24:26.4215967Z";
DateTime dateConversion = XmlConvert.ToDateTime(testDateExample,
XmlDateTimeSerializationMode.Utc);
Console.WriteLine(dateConversion);
Note that you should already have received a warning about the overload you're currently using, as it's deprecated. I received this warning when compiling your code:
Test.cs(12,35): warning CS0618: 'System.Xml.XmlConvert.ToDateTime(string)' is
obsolete: 'Use XmlConvert.ToDateTime() that takes in
XmlDateTimeSerializationMode'
Always pay attention to warnings like this.
See more on this question at Stackoverflow