System.Xml.XmlConvert.ToDateTime Method

Converts the string to a DateTime equivalent.

Syntax

public static DateTime ToDateTime (string s, string[] formats)

Parameters

formats
An array containing the format structures to apply to the converted DateTime. Valid formats include "yyyy-MM-ddTHH:mm:sszzzzzz" and its subsets.
s
The string to convert.
formats
An array containing the format structures to apply to the converted DateTime. Valid formats include "yyyy-MM-ddTHH:mm:sszzzzzz" and its subsets.

Returns

A DateTime equivalent of the string.

Exceptions

TypeReason
ArgumentNullException s is a null reference.
FormatException

s or an element of formats is string.Empty.

-or-

s does not contain a date and time that corresponds to any of the elements of formats.

Remarks

This method allows multiple formats for the string to be validated against.

Example

The following example converts a string to a DateTime and writes the result to the console.

C# Example

using System;
using System.Xml;

public class App {

  public static void Main() {

    String someDate = "1966-09-19T03:45:11Z";
    String[] datetimeFormats = new String[]
      {"HH:mm:ss", "yyyy-MM-ddTHH:mm:ssZ"};
    DateTime dateTime =
      XmlConvert.ToDateTime(someDate, datetimeFormats);
    Console.WriteLine( "{0}", dateTime.ToString() );
  }
}

The output is

9/18/1966 8:45:11 PM

Requirements

Namespace: System.Xml
Assembly: System.Xml (in System.Xml.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0