Skip to content

Instantly share code, notes, and snippets.

@tusbar
Created April 29, 2012 12:20
Show Gist options
  • Save tusbar/2550046 to your computer and use it in GitHub Desktop.
Save tusbar/2550046 to your computer and use it in GitHub Desktop.
Utility to parse Microsoft's JSON dates (JavaScriptSerializer, DataContractJsonSerializer)
define([
"underscore"
], function (_) {
return {
_msJsonDateFormat: /\/Date\((\d+)(?:([\-+])(\d+))?\)\//i,
toJSON: function (date) {
if (!_.isDate(date)) {
return null;
}
var offset = date.getTimezoneOffset() * 60000;
var utcTime = date.getTime() + offset;
return "/Date(" + utcTime + ")/";
},
parse: function (msJsonDate) {
var res = this._msJsonDateFormat.exec(msJsonDate);
if (!res) {
return null;
}
var ts = parseInt(res[1], 10);
var offset = 0;
if (!_.isUndefined(res[2]) && !_.isUndefined(res[3])) {
var east = res[2] == "+", tzoffset = res[3];
var hh = parseInt(tzoffset.slice(0, 2), 10)
, mm = parseInt(tzoffset.slice(2), 10);
offset = (hh * 60 + mm) - new Date().getTimezoneOffset();
if (east) offset = -offset;
}
return new Date(ts + offset * 60000);
}
};
});
@wild0ne
Copy link

wild0ne commented Jan 9, 2019

you have some bugs here, don't you?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment