XmlConvert.ToDateTimeOffset Method (String, String)
[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]
Converts the supplied String to a DateTimeOffset equivalent.
Assembly: System.Xml (in System.Xml.dll)
Parameters
- s
- Type: System.String
The string to convert.
- format
- Type: System.String
The format from which s is converted. The format parameter can be any subset of the W3C Recommendation for the XML dateTime type. For more information see XML Schema Part 2: Datatypes. The string s is validated against this format.
| Exception | Condition |
|---|---|
| ArgumentNullException | s is null. |
| FormatException | s or format is an empty string or is not in the specified format. |
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.
String xmlString =
@"<?xml version='1.0'?>
<transactions>
<transaction>
<id>123456789</id>
<amount>1.00</amount>
<currency>USD</currency>
<time>2007-08-03T22:05:13-07:00</time>
</transaction>
</transactions>";
StringBuilder output = new StringBuilder();
// Create an XmlReader
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
reader.ReadToFollowing("time");
string time = reader.ReadElementContentAsString();
// Specify a format against which time will be validated before conversion to DateTimeOffset
// If time does not match the format, a FormatException will be thrown.
// The specified format must be a subset of the W3C Recommendation for the XML dateTime type
string format = "yyyy-MM-ddTHH:mm:sszzzzzzz";
try
{
// Read the element contents as a string and covert to DateTimeOffset type
DateTimeOffset transaction_time = XmlConvert.ToDateTimeOffset(time, format);
output.AppendLine(transaction_time.ToString());
}
catch (Exception e)
{
output.Append(e);
}
}
// Display the output to the TextBlock control
OutputTextBlock.Text = output.ToString();