How can I convert a date value serialized in JSON to Moment?
E.g. a date is serialized as "Date":"\/Date(1488228437000+0100)\/" by a webservice I make my requests.
Thanks in advance!
function onWebResponse(code, data) {
if (code != 200) {
return;
}
var date = data["Date"];
// no real error checking
// assumes '\/Date(...)\/'
date = date.substring(7, date.length() - 3);
var options = [
"-",
"Z",
"+"
];
var sign = 0;
var pos;
for (var i = 0; i < 3; ++i) {
pos = date.find(options);
if (pos != null) {
sign = i - 1;
break;
}
}
// didn't find +, - or Z
if (pos == null) {
pos = date.length();
}
// exclude the milliseconds...
var timestamp = date.substring(0, pos - 3).toNumber();
if (sign != 0) {
var offset = date.substring(pos + 1, date.length());
// convert to a number in base 10
offset = offset.toNumber();
var hh = (offset / 100) * 3600;
var mm = (offset % 100) * 60;
// need to subtract the zone offset to get back to UTC time
timestamp -= sign * (hh + mm);
}
// the value passed to the init method is a utc timestamp
var moment = new Time.Moment(timestamp);
// do something with moment...
}
[/code]
the number has 3 extra trailing 0's
Uhh.. That is not valid JSON. It looks like you may be receiving data that uses some system-specific extension. If you can, it would be good to fix the server side so that it provides JSON clean data (just the UTC timestamp should be sufficient). If you don't want to do that, then you need to extract the string, then you need to parse it.
The code might look something like the following completely untested code...function onWebResponse(code, data) {
if (code != 200) {
return;
}
var date = data["Date"];
// no real error checking
// assumes '\/Date(...)\/'
date = date.substring(7, date.length() - 3);
var options = [
"-",
"Z",
"+"
];
var sign = 0;
var pos;
for (var i = 0; i < 3; ++i) {
pos = date.find(options);
if (pos != null) {
sign = i - 1;
break;
}
}
// didn't find +, - or Z
if (pos == null) {
pos = date.length();
}
// exclude the milliseconds...
var timestamp = date.substring(0, pos - 3).toNumber();
if (sign != 0) {
var offset = date.substring(pos + 1, date.length());
// convert to a number in base 10
offset = offset.toNumber();
var hh = (offset / 100) * 3600;
var mm = (offset % 100) * 60;
timestamp += sign * (hh + mm);
}
// the value passed to the init method is a utc timestamp
var moment = new Time.Moment(timestamp);
// do something with moment...
}
[/code]
Thanks, it works! :)
I found 2 small bugs (mispellings) in it:
date = date.substring(7, date.length() - 3); should be
date = date.substring(6, date.length() - 3);
and
var mm = (offset % 100) * 60; should be
var mm = (offset / 100) * 60;
date = date.substring(7, date.length() - 3); should be
date = date.substring(6, date.length() - 3);
var mm = (offset % 100) * 60; should be
var mm = (offset / 100) * 60;