0

I have got a Date returned from an Api as a Json object which looks like this: Date(1371510000000) When I open internet Explorer and paste the following in the url: javascript:alert(Date(1371510000000)) I get an alert reading the date 19 June 2013 (which is correct).

However when I deserialize this date in .NET using NewtonSoft's Json deserializer as shown below:

var x = Newtonsoft.Json.JsonConvert.DeserializeObject<DateTime>("\"/Date(1371510000000)/\"");

It parses the date as 17 June 2013 (which is incorrect).

Is there anything that I am doing incorrectly ?

Thanks.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Whiz Kid
  • 31
  • 1
  • 3
  • Seems like an issue with local time: http://stackoverflow.com/questions/948532/how-do-you-convert-a-javascript-date-to-utc – Pragmateek Jun 19 '13 at 11:48
  • I have inserted the parameter JSonSerializerSettings with my local culture, timezone info but the problem is still there. – Whiz Kid Jun 19 '13 at 12:14
  • Why do you believe that "19 June 2013" is correct for 1371510000000? Running your javascript doesn't give the same result each time. I don't think your javascript is doing what you think. – MerickOWA Sep 10 '13 at 21:10
  • Might be very old, but you need to write: `javascript:alert(new Date(1371510000000))` – Daniel Tiru Jun 16 '14 at 13:18

1 Answers1

0

The javascript Date object is something that is not serializable by .Net,

what you do is fix the date before you transfer your object:

function fixDate(date) {
    if (date != undefined && date != null && date.getDate) {
        var curr_date = date.getDate();
        var curr_month = date.getMonth() + 1; //Months are zero based
        var curr_year = date.getFullYear();
        date = curr_date + "/" + curr_month + "/" + curr_year;
        date = date.replace(/\b\d\b/g, '0$&');
    }
    return date;
}

this code is for the "dd/MM/yyyy" format , but you can format it how ever you like.

remember to choose the specific format in your server as well

Royi Mindel
  • 1,258
  • 12
  • 35
  • I don't understand why the browser deserializes the same date correctly. Isn't there any way of making .NET do the same ? – Whiz Kid Jun 19 '13 at 11:50
  • When you run that in the browser it runs the javascript code, .Net doesn't have the same deserializers – Royi Mindel Jun 19 '13 at 12:05