Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a JSON date into a C# DateTime

Tags:

json

c#

datetime

i have an API that get information from targetProcess and put that information in sql tables.

the issue comes when a targetProcess field is date because i recieved it as json date "/Date(1409202000000-0500 )/".

How can i convert this json date to Datetime in c#?

i have been trying add extra quotes like the asnwer in this StackOverflow Post but it doesnt work.

i tried replace the the word Date for only use 1409202000000-0500 in

DateTime dotNetDate = new DateTime(1970, 1, 1);
dotNetDate = dotNetDate.AddMilliseconds(Convert.ToInt64(1409202000000-0500) 

i use too JSON.NET as bellow

string sa = "/Date(1409202000000-0500 )/"
DateTime dt = new DateTime();
dt = JsonConvert.DeserializeObject<DateTime>(sa);

but it doesnt work too,

so the question is....How can i convert this json date to Datetime in c#?

like image 734
Victor Hernandez Avatar asked Mar 31 '17 00:03

Victor Hernandez


2 Answers

You need to manually wrap your string "programatically" in quotes to ensure that it properly formatted correctly:

string sa = @"""" + "/Date(1409202000000-0500 )/" + @"""";
DateTime dt = JsonConvert.DeserializeObject<DateTime>(sa);

If you need to call it multiple times (which it seems like you do), just move the wrapping responsibility to a method:

public string WrapStringInQuotes(string input)
{
    return @"""" + input + @"""";
}
like image 157
David L Avatar answered Sep 20 '22 12:09

David L


The issue is with your date string. instead of

string sa = "/Date(1409202000000-0500 )/"

try

string sa = @"""/Date(1409202000000-0500)/""";

Change your code :

 string sa = @"""/Date(1409202000000-0500)/""";
            DateTime dt = new DateTime();
            dt = JsonConvert.DeserializeObject<DateTime>(sa);
            // dt = "2014-08-28 3.00.00 PM"
like image 38
Santhosh Avatar answered Sep 20 '22 12:09

Santhosh