Friday, August 17, 2012

How to convert string to DateTime

Hi everybody,
just because I need store more knowledge than my brain can handle it I am posting about this :) And maybe someone finds it useful too....

If you receive the date as a string, you have to parse it to the DateTime. After that you can do all magic things which are not available for the string :)

//Received string
string dateString = "2.7.2012  13:55:07";
//To prevent differences between time zone you have to specify culture info
IFormatProvider theCultureInfo = new System.Globalization.CultureInfo("cs-CZ", true);

//Parsing time :)
DateTime dateDateTime= DateTime.ParseExact(myDate, "d.M.yyyy  HH:mm:ss", theCultureInfo);
//Now you can look what you did...
Console.WriteLine(dateDateTime.ToString("dd-MM-yyyy HH:mm"));

The list of culture info is here: http://www.csharp-examples.net/culture-names/

And little bit about SharePoint.
Because SharePoint DateTime conforms to ISO 8601 you don't need to use ParseExact method and you will be able to use just DateTime.Parse method. Also when you need to fill DateTime field in SP, this source code might be a helpful for you:
DateTime nowDate = DateTime.Now;
string spFormat = Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(nowDate);

Happy coding :)