Parsing DateTime values in C#

Freshness Warning
This post is more than 2 years old. Please bear in mind its age when reading.

Just a post to outline a few extra ways of parsing dates in C#. These are useful for internationalised apps.

try
{
    //Tell the parser to expect a en-GB (culture) date
    DateTime myDate = DateTime.Parse("20/02/2010", new CultureInfo("en-GB"));

 

    //Tell the parser to expect a date with a specific format
    DateTime myDateExact = DateTime.ParseExact("20/02/2010", "dd/MM/yyyy", null);

    //Tell the parser to expect a date with specific format
   //with exact hours, minutes and seconds
    DateTime dtParseExact = DateTime.ParseExact("20/02/2010 00:00:02", "dd/MM/yyyy HH:mm:ss", null);

    Console.WriteLine(string.Format("{0} = {1}", "myDate", myDate));
    Console.WriteLine(string.Format("{0} = {1}", "myDateExact", myDateExact));
    Console.WriteLine(string.Format("{0} = {1}", "dtParseExact", dtParseExact));
}
catch (FormatException ex)
{
    Console.WriteLine(ex.ToString());
}
 

 

I'm running the 39th BMW Berlin Marathon on 30th September 2012 for the British Lung Foundation, who are currently funding research on the prevention of lung damage in COPD and many other areas related to lung disease.

I'm participating with my sister Claire Kewney and, on behalf of the charity, would appreciate even the smallest donation. My own JustGiving page is here, our team page is here.

if you're in the UK, you can also donate using your mobile phone by texting NKEW82 £5 (or any amount) to 70070. Your donation will be appreciated!

Comments

  1. Nice post! Thanks...
Your Comment
Your Name
E-mail Address (This won't be published)
Website URL

You can manage your Kewney.com account by logging in. [ Log On ]