How to convert a string “yyyy-MM-ddZ” to a date time with .net?
Question
I am having problems converting a string in the format "yyyy-MM-ddZ" using VB.net.
For example I have the string "2007-10-21Z".
Using CDate or TryParse it comes out to 10/20/2007 instead of 10/21/2007.
I'm not understanding how the Z affects the date string so that when it is parsed it results in the day before.
From what I understand Z specifies the zero timezone. But the date string has no time information. How does this work?
Solution
Try
DateTime.ParseExact("2007-10-21Z", "yyyy-MM-ddZ", CultureInfo.InvariantCulture);
OTHER TIPS
It's interpreting the date as midnight Zulu (GMT) time and then converting it back to your local time zone. If you're in the States that would be between 3:00PM to 7:00 PM in the previous day.
Adding "Z" to the date specifies that time is UTC. When you CDate of TryParse the date, it is converting it to local time.
Wow, that's interesting. I try in C# DateTime.Parse("2008-10-31").ToString(); and the result is "10/30/2008 5:00:00 PM".
I can't wait for an answer!