Reputation: 89
I am using JSON.NET's LINQ to JSON to parse data, which includes dates. My sample JSON looks like this:
{"2013" : [
{ "date":"2/5/2013 11:13 AM","id":23 }],
"2012" : [
{ "date":"28/9/2012 5:29 PM","id":24 }]
}
The format of the date is in d/m/yyyy h:mm. I tried parsing it first using DateTime.Parse:
var postTitles = jobject.Children().SelectMany(x => x.First).
Select(p =>
new Report
{
Date = DateTime.Parse((string)p["date"]),
Height = (int)p["height"]
});
However, it throws a FormatException on the second date so I tried using DateTime.ParseExact instead:
var postTitles = jobject.Children().SelectMany(x => x.First).
Select(p =>
new Report
{
Date = DateTime.ParseExact(p["date"].ToString(), "dd/mm/yyyy hh:mm", new
CultureInfo("en-US")),
Height = (int)p["height"]
});
This time, I get a FormatException on the first date. Are there any alternatives on how to parse this dates? I tried using Extension Methods as I am used to doing XML but it seems my extension methods are not recognized.
Upvotes: 0
Views: 611
Reputation: 1502106
Your format string for ParseExact
is very broken. Basically, you really need to pay attention to the format of your actual data, and look at the MSDN documentation for custom date/time strings. You can't just put any old pattern in and expect it to work: it's got to match your data.
So you probably want a format string of "d/M/yyyy h:mm tt". I would also suggest using the invariant culture:
Date = DateTime.ParseExact(p["date"].ToString(), "d/M/yyyy h:mm tt",
CultureInfo.InvariantCulture);
(The invariant culture is mostly the same as the US culture, but the important aspect is that it indicates that this is intended for machine-generated data rather than genuinely US-centric data.)
There may well be a better way of doing this in JSON.NET, but that should at least be a starting point.
Upvotes: 4