CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Peter's Gekko

public Blog MyNotepad : Imho { }

Parsing custom dates using ParseExact

All types in the .Net framework have a Parse method. This takes a string and tries to translate it into a value of the intended type. Like this

int i = int.Parse("7");

 

This will throw an exception when the contents of a string cannot be parsed as an integer value. The TryParse method is more foregiving

string myString = "7";

if (! int.TryParse(myString, out i))

    Log.Debug("That's not an int !");

 

These methods have overloads which accept info on the format of the string to be parsed. You will really need these when it comes to parsing date values. Alas the overloaded parameters are of somewhat scary types like an IFormatProvider interface.

Far easier to use is the ParseExact method which takes a custom format as parameter. In the text file I had to work through dates were encoded as yyyyMMdd. Instead of working through format providers the ParseExact method accepts this custom format string itself.

try

{

  

    DateTime ingangsDatum = DateTime.ParseExact(msg.Datum_Aanst, "yyyyMMdd", CultureInfo.CurrentCulture);

}

catch (FormatException fex)

{

    AfgeKeurd(string.Format("Datum aanstelling {0} niet herkend als geldige datum", msg.Datum_Aanst));

    return;

}

 

Forgive me the double dutch, but the snippet should speak for itself. afaik there is no TryParseExact member, I have to catch a formatexception.

Another error I often see (and make) is using "yyyymmdd" as format string. Which is perfectly valid but it will take the minutes, not the Month.


Published Feb 28 2008, 12:16 PM by pvanooijen
Filed under:

Comments

Sander said:

There is a DateTime.TryParseExact() method.

msdn2.microsoft.com/.../system.datetime.tryparseexact.aspx

# February 29, 2008 3:20 AM

pvanooijen said:

Hi Sander !.

You're right. New in 3.5. ParseExact is also available in 2.0

# February 29, 2008 4:35 AM

Sander said:

Ehm.. no, TryParseExact was there in version 2.0 too.

msdn2.microsoft.com/.../system.datetime.tryparseexact(VS.80).aspx

# March 10, 2008 6:54 AM

pvanooijen said:

You're right.. Me or Resharper's intellisense missed that when writing this post.

Thanks for correcting !

# March 11, 2008 4:16 PM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add
Check out Devlicio.us!