简体   繁体   中英

Parsing a JSON Date/Time value using the Windows.Data.Json library in C#/WinRT project

I am receiving a JSON DateTime value that looks like the following: "/Date(1313438502992)/"

How can I convert it to the proper DateTime value in C# using the Windows.Data.Json library?

Using the following code results in an incorrect DateTime value being reported:

string dateValue = value.GetString();
//we get a value like "/Date(1313438502992)/"

dateValue = dateValue.Replace("/Date(", "");
dateValue = dateValue.Replace(")/", "");

var PublishDate = new System.DateTime(Convert.ToInt64(dateValue));

Not sure if the JSON encoder and the C# DateTime object use the same concept of the epoch. Any guidance would be deeply appreciated.

JSON value should be number of milliseconds since January 1st 1970 UTC . Try the following code if it gives you the expected result:

var match = Regex.Match(dateValue, @"/Date\((?<millisecs>-?\d*)\)/");
var millisecs = Convert.ToInt64(match.Groups["millisecs"].Value);
var date = new DateTime(1970, 1, 1).AddMilliseconds(millisecs);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM