C# DateTime TryParse(String, DateTime)

Description

DateTime TryParse(String, DateTime) converts the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.

Syntax

DateTime.TryParse(String, DateTime) has the following syntax.


public static bool TryParse(
  string s,
  out DateTime result
)

Parameters

DateTime.TryParse(String, DateTime) has the following parameters.

  • s - A string containing a date and time to convert.
  • result - When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. The conversion fails if the s parameter is null, is an empty string (""), or does not contain a valid string representation of a date and time. This parameter is passed uninitialized.

Returns

DateTime.TryParse(String, DateTime) method returns true if the s parameter was converted successfully; otherwise, false.

Example

The following example passes a number of date and time strings to the DateTime.TryParse(String, DateTime) method.


using System;// ww w.  j av a 2s .  c o  m
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 »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version