Gilad Lavian's Blog

In Development

March 2008 - Posts

Parsing DateTime formats

A few ways to handle dates in application:

try
{
    //Tells the parser to expect a he-IL (culture) date format
    DateTime dateParse = DateTime.Parse("28/02/2008", new CultureInfo("he-IL"));

    //Tells the parser to expect a date with specific date format
    DateTime dateParseExact = DateTime.ParseExact("28/02/2008", "dd/MM/yyyy", null);

    //Tells the parser to expect a date with specific date format 
    //with exact hours, minutes and seconds
    DateTime dateTimeParseExact = 
        DateTime.ParseExact("28/02/2008 23:29:02", "dd/MM/yyyy HH:mm:ss", null);

    Console.WriteLine(string.Format("{0} = {1}", "dateParse", dateParse));
    Console.WriteLine(string.Format("{0} = {1}", "dateParseExact", dateParseExact));
    Console.WriteLine(string.Format("{0} = {1}", "dateTimeParseExact", dateTimeParseExact));
}
catch (FormatException ex)
{
    Console.WriteLine(ex.ToString());
}