I have a WCF service that serves some dates to my javascript. I want to manipulate the date, but it arrives in the javascript looking like this:
/Date(1361145600000+0000)/
I know this is the miliseconds since 1970/01/01, but I havent been able to figure out how to convert it to a javascript Date.
Do I need to use a regex or trim the text to extract the miliseconds, and then use it like this:
new Date(miliseconds)
Surely there must be an easier way?
If the '+0000' is a standard timezone offset, the first 2 digits are hours, the last two, minutes.
Presumably it is not always '0000'-
You need to add(or subtract) the milliseconds difference from UTC to the first integral part to return the correct Date.
function timeconvert(ds){
var D, dtime, T, tz, off,
dobj= ds.match(/(\d+)|([+-])|(\d{4})/g);
T= parseInt(dobj[0]);
tz= dobj[1];
off= dobj[2];
if(off){
off= (parseInt(off.substring(0, 2), 10)*3600000)+
(parseInt(off.substring(2), 10)*60000);
if(tz== '-') off*= -1;
}
else off= 0;
return new Date(T+= off).toUTCString();
}
timeconvert('Date(1361145600000)+0000');
//returned value: (String UTC)
Mon, 18 Feb 2013 00:00:00 GMT
If the Dates ARE always in UTC ('+0000') you can just pull the significant digits from the string-
function timeconvert(ds){
var d=ds.match(/(\d+)/)[1];
return new Date(+d).toUTCString();
}
timeconvert('Date(1361145600000)+0000)');
// returned value: (String UTC)
Mon, 18 Feb 2013 00:00:00 GMT
Code proposed by kennebec has a bug with a dates, that lower than 1 January 1970. For example, Date(-124054000000+0300) is Wed Jan 26 1966 07:33:20
Fixed code : http://output.jsbin.com/cejolu/3/edit?js,console
function timeconvert(ds){
var D, dtime, T, tz, off,
dobj = ds.match(/(-?\d+)|([+-])|(\d{4})/g);
T = parseInt(dobj[0], 10);
tz = dobj[1];
off = dobj[2];
if (off) {
off = (parseInt(off.substring(0, 2), 10) * 3600000) + (parseInt(off.substring(2), 10) * 60000);
if(tz == '-') off *= -1;
}
else off= 0;
return new Date(T += off).toUTCString();
}
Test for the newest changes :
console.log(timeconvert("Date(-124054000000+0300)"));
console.log(timeconvert('Date(1361145600000)+0000'));
console.log(timeconvert("Date(0+0300)"));
console.log(timeconvert("Date(-2+0200)"));
console.log(timeconvert("Date(-860000000000+1100)"));
/* Output */
"Wed, 26 Jan 1966 07:33:20 GMT"
"Mon, 18 Feb 2013 00:00:00 GMT"
"Thu, 01 Jan 1970 03:00:00 GMT"
"Thu, 01 Jan 1970 01:59:59 GMT"
"Thu, 01 Oct 1942 18:06:40 GMT"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With