Parsing DateTime values in C#

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());
}
 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.