Export (0) Print
Expand All

XmlConvert.ToDateTimeOffset Method (String, String[])

Converts the supplied String to a DateTimeOffset equivalent.

Namespace:  System.Xml
Assemblies:   System.Xml (in System.Xml.dll)
  System.Xml.ReaderWriter (in System.Xml.ReaderWriter.dll)

public static DateTimeOffset ToDateTimeOffset(
	string s,
	string[] formats


Type: System.String

The string to convert.

Type: System.String[]

An array of formats from which s can be converted. Each format in formats can be any subset of the W3C Recommendation for the XML dateTime type. (For more information see http://www.w3.org/TR/xmlschema-2/#dateTime.) The string s is validated against one of these formats.

Return Value

Type: System.DateTimeOffset
The DateTimeOffset equivalent of the supplied string.

If the offset specified within the input string will cause an overflow in the deserialized representation of the DateTimeOffset, a FormatException is thrown.

When more than seven digits are specified for fractional seconds, the value is rounded. For example, 00000004 becomes 0000000 and 00000005 becomes 0000001.

The following example demonstrates how to read a string from an XML file and use the ToDateTimeOffset method to convert the string to a DateTimeOffset type. The input string must validate against one of the specified formats before being converted.

using System;
using System.Xml;

class Example
    static void Main()
        // Create an XmlReader, read to the "time" element, and read contents as type string
        XmlReader reader = XmlReader.Create("transactions.xml");
        string time = reader.ReadElementContentAsString();

        // Specify formats against which time will be validated before conversion to DateTimeOffset 
        // If time does not match one of the specified formats, a FormatException will be thrown. 
        // Each specified format must be a subset of the W3C Recommendation for the XML dateTime type 
        string[] formats = {"yyyy-MM-ddTHH:mm:sszzzzzzz", "yyyy-MM-ddTHH:mm:ss", "yyyy-MM-dd"};
            // Read the element contents as a string and covert to DateTimeOffset type
            DateTimeOffset transaction_time = XmlConvert.ToDateTimeOffset(time, formats);
        catch (Exception e)

The example uses the transactions.xml file.

<?xml version="1.0"?>

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5 SP1, 3.0 SP1, 2.0 SP1

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8
© 2015 Microsoft