Peter's Gekko

Sponsors

The Lounge

News

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
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.


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

[Advertisement]

Comments

Sander wrote re: Parsing custom dates using ParseExact
on Fri, Feb 29 2008 3:20 AM

There is a DateTime.TryParseExact() method.

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

pvanooijen wrote re: Parsing custom dates using ParseExact
on Fri, Feb 29 2008 4:35 AM

Hi Sander !.

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

Sander wrote re: Parsing custom dates using ParseExact
on Mon, Mar 10 2008 6:54 AM

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

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

pvanooijen wrote re: Parsing custom dates using ParseExact
on Tue, Mar 11 2008 4:16 PM

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

Thanks for correcting !

Add a Comment

(required)  
(optional)
(required)  
Remember Me?