Reputation: 2327
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.
Upvotes: 6
Views: 7230
Reputation: 10397
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
Upvotes: 0
Reputation: 1060
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)'));
Upvotes: 0
Reputation: 69905
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;
}
Upvotes: 0
Reputation: 18013
not that I know... this is the function i'm using, just in case ...
function toDateFromJson(src) {
return new Date(parseInt(src.substr(6)));
}
Upvotes: 7