I have a 5 digit number stored in a variable. The next step is to convert the number to a date. for example
var x = 20151506;
The above number has to be converted to:
Thu June 15 2015 06:35:50
I have a 5 digit number stored in a variable. The next step is to convert the number to a date. for example
var x = 20151506;
The above number has to be converted to:
Thu June 15 2015 06:35:50
Please note that you must first specify the time in your original date value for it to be formatted and included correctly in your output. Thus the following will not provide the time element as you're looking for.
Referencing this SO answer:
function parse(str) {
var y = str.substr(0,4),
m = str.substr(6,2) - 1,
d = str.substr(4,2);
var D = new Date(y,m,d);
return (D.getFullYear() == y && D.getMonth() == m && D.getDate() == d) ? D : 'invalid date';
}
Usage:
parse('20151506');
Output:
Mon Jun 15 2015 00:00:00 GMT-0500 (Central Daylight Time)
or in your case
parse(x.toString());
Output:
Mon Jun 15 2015 00:00:00 GMT-0500 (Central Daylight Time)
Code snippet provided below:
var x = 20151506;
function parse(str) {
var y = str.substr(0,4),
m = str.substr(6,2) - 1,
d = str.substr(4,2);
var D = new Date(y,m,d);
return (D.getFullYear() == y && D.getMonth() == m && D.getDate() == d) ? D : 'invalid date';
}
//document.write (parse('20151506'));
document.write (parse(x.toString()));
To convert that "number" in to a Date you'll have to split it into the relevant year month day (hours, minutes and seconds appear to be missing).
var x = 20151506;
var month = x % 100;
var day = Math.floor(x % 10000 / 100);
var year = Math.floor(x / 10000);
var date = new Date(year, month - 1, day)
This will give you the value of date in whateve your local timezone is - Mon Jun 15 2015 00:00:00 GMT+0100 (GMT Daylight Time)
.
Not sure where you get the your time part from?