Showing posts with label DateTime conversion. Show all posts
Showing posts with label DateTime conversion. Show all posts

Wednesday, June 16, 2010

Convert UTC date using Convert.ToDateTime Surprise

While working on a project I had to convert a date string to DateTime object. As the date value was coming from SharePoint it was a UTC date - "2010-01-01T00:00:00Z". So looking at the date value I expected that Convert.ToDateTime or DateTime.Parse will return me 1/1/2011 12:00:00 but to my surprise I was getting 12/31/2010 7:00:00 PM I quickly realized the mistake I was doing and searched MSDN and thanks to SPUtility class for the rescue. So convert UTC date string to a DateTime object use the following method to get the correct date -

objectDateString is object type with value "2010-01-01T00:00:00Z"

SPUtility.CreateSystemDateTimeFromXmlDataDateTimeFormat(objectDateString.ToString()) returns {1/1/2011 12:00:00 AM} System.DateTime

or the following will also return correct date -

Convert(objectDateString.ToString()).ToDateTime().ToUniversalTime()



using DateTime.Parse or Convert.ToDateTime I was getting wrong dates -
DateTime.Parse(objectDateString.ToString()) returns {12/31/2010 7:00:00 PM} System.DateTime

Convert.ToDateTime("2010-01-01T00:00:00Z") return  {12/31/2010 7:00:00 PM}

Again lesson learned to treat DateTime values with respect. :)

For more information in this -
http://www.jamestsai.net/Blog/post/SPRegionalSettingsGlobalTimeZones-How-to-build-world-clock-get-time-zones-information-in-SharePoint.aspx

http://www.novolocus.com/2008/07/31/sharepoint-web-services-and-utc-time-fun-and-games/