Try to parse string to DateTime and returns a value that indicates whether the conversion succeeded in CSharp

Description

The following code shows how to try to parse string to DateTime and returns a value that indicates whether the conversion succeeded.

Example


using System;/* ww w. j av  a2s .  c  om*/
public class MainClass{
  public static void Main(String[] argv){  
    string[] dateStrings = {"05/01/2014 14:57:32.8", "2014-05-01 14:57:32.8", 
                            "2014-05-01T14:57:32.8375298-04:00", 
                            "5/01/2008 14:57:32.80 -07:00", 
                            "1 May 2008 2:57:32.8 PM", "16-05-2014 1:00:32 PM", 
                            "Fri, 15 May 2014 20:10:57 GMT" };
    DateTime dateValue;
    
    foreach (string dateString in dateStrings)
    {
       if (DateTime.TryParse(dateString, out dateValue)) 
          System.Console.WriteLine("  Converted '{0}' to {1} ({2}).", dateString, 
                            dateValue, dateValue.Kind);
       else
          System.Console.WriteLine("  Unable to parse '{0}'.", 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