6

I've the following problem:

I retrieve a DateTime object from SQL Server and pass it via JSON (using $.ajax) to Javascript. I have experienced difficulty trying to convert the retrieved object to a Date object in javascript. The retrieved object is a string of value "/Date(615592800000)/". I think the value is an epoch time.

My question is, is there another way of retrieving the date object than to use regex to select the epoch value and then create a new Date object?

I'm fairly new to JS, so any help would be appreciated.

4 Answers 4

7

not that I know... this is the function i'm using, just in case ...

function toDateFromJson(src) {
    return new Date(parseInt(src.substr(6)));
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thx. Not exactly what I was looking for, but this is quite simple and usable.
0

Try this. Pass the date string which you get to the below function. It will give you the JavaScript date object.

function (val) {
        var reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/;
        var reMsAjax = /^\/Date\((d|-|.*)\)[\/|\\]$/;


            if (val)) {
                        var a = reISO.exec(val);
                        if (a) {
                            val = new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));
                            return val;
                        }
                        a = reMsAjax.exec(val);
                        if (a) {
                            var b = a[1].split(/[-+,.]/);
                            val = new Date(b[0] ? +b[0] : 0 - +b[1]);
                            return val;
                        }
                    }

       return val; 
    }

Comments

0

This is because JSON as standard does not have a DateTime format - vendors are free to mark it down as they want. WCF has this weird format of /Date()/ I faced this just a couple of months ago. Using Jquery and Jquery UI it will look like that. controlId is the identifier of an element with

var converted = eval(original.replace(/\/Date\((\d+)\)\//gi, 'new Date($1)'));

Comments

0

The regex way is the perfectly correct way to go.

var msDateRegex = /"\\\/Date\((-?\d+)\)\\\/"/g;

var msDateJsonConverter = function(data) {
    return JSON.parse($.trim(data.replace(msDateRegex, '{"__date":$1}')), function(key, value) {
        return value && typeof value.__date == "number" ? new Date(value.__date) : value;
    });
};

$.ajaxSetup({ converters: { "text json": msDateJsonConverter } });

See: http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.