16

After serializing an object with DateTime field with JavaScriptSerializer, I see that the DateTime field looks like this:

EffectiveFrom: "/Date(1355496152000)/"

How can I convert this string to Javascript Date object?

Michael Gaskill
  • 7,913
  • 10
  • 38
  • 43
dragonfly
  • 17,407
  • 30
  • 110
  • 219
  • 3
    This might help you http://codeasp.net/blogs/hajan/microsoft-net/1841/convert-net-serialized-json-datetime-to-javascript-date-object – Shreyos Adikari Apr 23 '13 at 08:03
  • possible duplicate of [Format a Microsoft JSON date?](http://stackoverflow.com/questions/206384/format-a-microsoft-json-date) – Michael Mar 03 '15 at 22:00

4 Answers4

20

UPDATE: This answer may not be appropriate in all cases. See JD's answer for an elegant solution that is likely better.

You could just "fix" the output from JavaScriptSerializer on the .Net side of things:

JavaScriptSerializer serializer = new JavaScriptSerializer();
var json = serializer.Serialize(this);
json = Regex.Replace(json,@"\""\\/Date\((-?\d+)\)\\/\""","new Date($1)");
return json;

This would change

EffectiveFrom: "/Date(1355496152000)/"

to

EffectiveFrom: new Date(1355496152000)

Which is directly consumable by Javascript

EDIT: update to accommodate negative dates

EDIT: Here is the Regex line for VB folks:

json = Regex.Replace(json, """\\/Date\((-?\d+)\)\\/""", "new Date($1)")

UPDATE 2016.11.20: With a lot more datetime handling in javascript/json behind me, I would suggest changing the regex to something as simple as

json = Regex.Replace(json,@"\""\\/Date\((-?\d+)\)\\/\""","$1");

The resulting value is valid JSON, and can be converted to a Date object on the javascript side.

It is also worth noting that moment.js (http://momentjs.com/docs/#/parsing/) handles this format happily enough.

moment("/Date(1198908717056-0700)/");
Community
  • 1
  • 1
Jefferey Cave
  • 2,507
  • 1
  • 27
  • 46
  • 3
    Good idea. Why does the JavaScriptSerializer use a format unusable by JavaScript though? – xr280xr May 13 '14 at 17:45
  • 1
    Two reasons. First, when the JSON format was created they left out date literals. Second, while this is "usable directly by javascript" it is usable only in the sense that you have to use eval() and eval() is considered bad because it can be used in cross site scripting attacks. – Zack May 28 '14 at 18:07
  • 2
    json = Regex.Replace(json,@"\""\\/Date\((-?\d+)\)\\/\""","new Date($1)"); the number might be negative – Bastianon Massimo Jul 18 '14 at 10:21
  • @Kavius I can't get my JSON to pass a validation linter when I use that technique. Should it pass? – Corgalore Jun 15 '15 at 16:39
  • @Corgalore, as indicated by Zach, this is not true "JSON" so much as valid "Javascript". It will likely not pass a "JSON" validation. For strict JSON conformance, you may find one of the other answers more appropriate. – Jefferey Cave Jun 15 '15 at 16:51
  • Is there any way to get only Date in `MM//dd//YYYY` format ?. Tried the code and it worked but got DateTime in UTC format like `Thu Nov 10 2005 16:03:53 GMT+0530 (India Standard Time)` – Lara Nov 14 '16 at 12:45
  • @Lara Getting a Date object from JavaScript is one problem, formatting it for human consumption is another. I would suggest looking up javascript date formatting resouces, I personally use moment.js (often) – Jefferey Cave Nov 14 '16 at 13:14
12

There is an answer that may help you:

Parsing Date-and-Times from JavaScript to C#

If you want to parse datetime string to datetime value with javascript you must use "new Date" like this:

var data = new Date("1355496152000");
Community
  • 1
  • 1
Hakan KOSE
  • 751
  • 9
  • 16
8
var obj = { EffectiveFrom: "/Date(1355496152000)/" };

//parse the Date value and replace the property value with Date object:

var dateValue = parseInt(obj.EffectiveFrom.replace(/\/Date\((\d+)\)\//g, "$1"));
obj.EffectiveFrom = new Date(dateValue);
gp.
  • 8,074
  • 3
  • 38
  • 39
8

This is a bit of a hack, but the above seemed inelegant for what I'm trying to achieve, so in the object definition I'm serializing, I did this:

        /// <summary>Date of the record retention event or document date.
        /// </summary>
        public string DateOfRetentionEvent;
        [ScriptIgnore]
        public DateTime RetentionEventDate 
        {
            get
            {
                return _retentionEventDate;
            }
            set
            {
                _retentionEventDate = value;
                DateOfRetentionEvent = value.ToShortDateString();
            }
        }

The point being that, at least in my use case (deserialization never happens), the JSON doesn't really care what C# is doing with the date value. Adding [ScriptIgnore] to the DateTime value and giving an alternative view for the parser to output should do the trick. It does in my case:

{
    "DateToDispose": "1/1/2020",
    "DateOfRetentionEvent": "10/1/2014",
    "FullRetentionCode": "NR+5",
    "RetentionEvent": "NR",
    "RetentionPeriod": 5
}
J.D. Ray
  • 697
  • 1
  • 8
  • 22