Use DateTime.TryParseExact to Easily Parse Formatted String Dates

30. June 2009 09:57 by Dan in Development  //  Tags:   //   Comments (0)

I needed to parse a known string format (DDMMYYYY) into a DateTime object and as I started to write the code I thought it looked a bit nasty and there must be a better way:

   1: private DateTime ParseDate(string date)
   2: {
   3:     DBC.CheckPre("Date can't be null", !string.IsNullOrEmpty(date));
   4:     DBC.CheckPre("Date length should be 8 for importing (DDMMYYYY)", date.Length == 8);
   5:  
   6:     string dateToConvert = string.Format("{0}/{1}/{2}", date.Substring(0, 2), date.Substring(2, 2), date.Substring(4, 4));
   7:     DateTime convertedDate;
   8:  
   9:     if (!DateTime.TryParse(dateToConvert, out convertedDate))
  10:         throw new FormatException(string.Format("Unable to format date:{0}", date));
  11:  
  12:     return convertedDate;
  13: }

I'd seen DateTime.TryParseExact before but hadn't really looked into it until today, the MSDN documentation can be found at http://msdn.microsoft.com/en-us/library/h9b85w22.aspx.

I've used formatters such as:

return DateTime.Now.ToString("ddMMyyyy");

TryParseExact takes an argument of string formats allowing you easily parse a string like this:

   1: private DateTime ParseDate(string date)
   2: {
   3:     DBC.CheckPre("Date can't be null", !string.IsNullOrEmpty(date));
   4:     DBC.CheckPre("Date length should be 8 for importing (DDMMYYYY)", date.Length == 8);
   5:  
   6:     DateTime convertedDate;
   7:  
   8:     if (!DateTime.TryParseExact(date, "ddMMyyyy", new CultureInfo("en-GB"), DateTimeStyles.None, out convertedDate))
   9:         throw new FormatException(string.Format("Unable to format date:{0}", date));
  10:  
  11:     return convertedDate;
  12: }

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading