Tuesday, October 17, 2006

Manipulating a string into a DateTime


This is a common requirement in any application, this is what ive come across on my projects!

Date manipulation is very sensitive, there will always be the exception to the rules where a querky solution is required however ill list what worked for me..

Example dates "1/6/2005", "6/1/2005", "1-Jun-2005", "1st June 2005"

I use the DateTime.Parse function. Its a cool function but it does substitute current date values for missing or erroneous values. eg. if your missing the year it will use the current year. The default missing/eroneous time elements default to 12:00:00am. It is a flexible function that makes assumptions...

If you want to be specific and not use the defaults then use the DateTime.ParseExact. The IFormatProvider parameter is used to provide culture-specific information. If the IFormatProvider is null then it uses the current threads culture information.

If there is a format issue it will throw the System.FormatException


Code: Sample

DateTime dt1 = DateTime.Parse("Sep 2005");

DateTime dt2 = DateTime.ParseExact("Mon, 05 Sep 2005 14:13:30 GMT", ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", null);

No comments: