How do I parse this date format:
/Date(1402537043438+1000)/
to a C# DateTime?
I'm limited to .Net 3.5 and can't use a nuget package like Newtonsoft.
asked Sep 21, 2015 at 9:27
-
JavaScriptSerializer.Deserialize should be able to read that formatCodingIntrigue– CodingIntrigue2015年09月21日 09:32:49 +00:00Commented Sep 21, 2015 at 9:32
-
I get an excpetion "Invalid JSON primitive: ."Ev.– Ev.2015年09月21日 09:39:20 +00:00Commented Sep 21, 2015 at 9:39
1 Answer 1
JavaScriptSerializer (an external assembly, of sorts, but not a NuGet requirement) can parse those dates, but they need to have a \
at the start and end of the string, e.g.:
var date = "/Date(1402537043438+1000)/";
var parsedDate = new JavaScriptSerializer().Deserialize<DateTime>("\"" + date.Replace("/", "\\/") + "\"");
answered Sep 21, 2015 at 9:39
4 Comments
Ev.
Thanks for the fast reply. I'm more than happy to use use Framework stuff, but my string isn't quite in that format. Your's has some characters that are lacking in mine, specifically the leading escaped quotes and the additional backslashes
CodingIntrigue
@Ev. Yup, that's right. Your date is what I have in the
date
variable. What I'm doing is modifying that variable to make it a valid JSON format for the serializerEv.
I have just seen your update and I expect it to work. Seems kind of wacky that that string isn't more easily converted. Do you think that suggests my data is bad?
CodingIntrigue
Your data is fine, this is the format MS uses to represent a Date in JSON (it's actually the format the
JavaScriptSerializer
will serialize to) because JSON doesn't actually specify a way to handle Dates. It seems wacky, because it technically is just a wacky workaround to a limitation of the JSON format :)lang-js