Dave Tapson
Dave Tapson

Reputation: 850

C# Convert date from xml (which can vary format by locality) to DateTime datatype

I need to extract datetimes from xml in both long (yyyy-MM-dd HH:mm:ss) and short (yyyy-MM-dd) format from an xml doc. Date format can vary by locality e.g. MM/dd/yyyy vs yyyy-mm-dd.

The app is run in each locality so will know what the local localisation is.

Question: How do I 1. extract dates from the xml node inner text using whatever is the local date format 2. extract the dates using long or short format given that I may not know which has been supplied in the xml node

Upvotes: 2

Views: 1723

Answers (2)

Martin Staufcik
Martin Staufcik

Reputation: 9490

You might be interested in the methods DateTime.TryParseExact or DateTime.ParseExact. Then create a set of allowed format strings and loop throuh this set to test parse the date from the most specific formats first:

var formats = new List<string>();
formats.Add("yyyy-MM-dd HH:mm:ss");
formats.Add("yyyy-MM-dd");
formats.Add("MM/dd/yyyy");
formats.Add("yyyy-mm-dd");

DateTime parsedDate;
foreach(var format in formats)
{
    if (DateTime.TryParseDate(str, format, CultureInfo.InvariantCulture,   DateTimeStyles.None, out parsedDate))
    {   
        break;
    }
}

Edited: The correct format is ISO 8601 as described here:

What is the correct format to use for Date/Time in an XML file

If not using the standard format, there could be a conflict between similar formats, for example between dd/MM/yyyy and MM/dd/yyyy which are both valid in some regions.

Upvotes: 3

Richa Garg
Richa Garg

Reputation: 1926

As suggested by Panagiotis Kanavos, the dates in xml should be of the ISO8601 format. Here is an example of such :

string xmlInput =  @"
<root>
<element>
<timestamp time='2016-09-15T13:45:30'>
</timestamp>
</element>
<element>
<timestamp time='2016-10-16T13:45:30'>
</timestamp>
</element>
</root>";

XDocument  xdoc = XDocument.Parse(xmlInput);
var listOfDates = xdoc.Descendants("root").Elements("element").Select(x => DateTime.Parse(x.Element("timestamp").Attribute("time").Value,CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind)).ToList<DateTime>();
Console.WriteLine(listOfDates[0]);

Upvotes: 1

Related Questions