Try to parse string to DateTime with several possible formats in CSharp

Description

The following code shows how to try to parse string to DateTime with several possible formats.

Example


/* w w  w. j  a va 2  s  .  com*/
using System;
using System.Globalization;
public class MainClass{
  public static void Main(String[] argv){  
    string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                       "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                       "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                       "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                       "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
    string[] dateStrings = {"5/1/2014 6:32 PM", "05/01/2014 6:32:05 PM", 
                            "5/1/2014 6:32:00", "05/01/2014 06:32", 
                            "05/01/2014 06:32:00 PM", "05/01/2014 06:32:00"}; 
    DateTime dateValue;
    
    foreach (string dateString in dateStrings)
    {
       if (DateTime.TryParseExact(dateString, formats, 
                                  new CultureInfo("en-US"), 
                                  DateTimeStyles.None, 
                                  out dateValue))
          System.Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
       else
          System.Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
    }

    
  }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var