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?

2

4 Answers 4

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)/");
Sign up to request clarification or add additional context in comments.

7 Comments

Good idea. Why does the JavaScriptSerializer use a format unusable by JavaScript though?
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.
json = Regex.Replace(json,@"\""\\/Date((-?\d+))\\/\""","new Date($1)"); the number might be negative
@Kavius I can't get my JSON to pass a validation linter when I use that technique. Should it pass?
@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.
|
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");

Comments

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);

Comments

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
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.