I have a string with a date in it formatted like so: YYYYMMDDHHMMSS. I was wondering how I would convert it into a JavaScript Date object with JavaScript.
Thanks in
I find DateJS the best library for anything that has to do with converting, parsing and using dates in JavaScript. If you need that kind of conversions more often you should really consider using it in your application:
Date.parseExact("20091202051200", "YYYYMMDDHHMMSS");
Primitive version:
new Date(foo.slice(0, 4), foo.slice(4, 6) - 1, foo.slice(6, 8),
foo.slice(8, 10), foo.slice(10, 12), foo.slice(12, 14))
An explicit conversion of the strings to numbers is unnecessary: the Date()
function will do this for you.
There is no time zone information in your string. It most likely is GMT, so that should be accounted for when you make the Date. You can easily do the conversion with simple javascript methods.
Date.Brit= (function(){
return Date.parse('2/6/2009')> Date.parse('6/2/2009');
})()
var s= "20091202093000"
var D= s.match(/(\d{2})/g);
if(Date.Brit){
D.splice(2, 2, D[3],D[2]);
}
var day= new Date(Date.parse(D[2]+'/'+D[3]+'/'+
D[0]+D[1]+' '+D.splice(4).join(':')+' GMT'));
day.toUTCString()+'\n'+day
/* returned value: (String)
Wed, 02 Dec 2009 09:30:00 GMT
Wed Dec 02 2009 04:30:00 GMT-0500 (Eastern Standard Time)
*/
If you can use jQuery, jQuery.ui.datepicker has a utility function.
Date functions from this library can help: http://javascripttoolbox.com/lib/date/ , it's free and very simple to use.
If you want to do it yourself, I would suggest looking up the javascript regular expressions, as I guess that is the way to achieve this best
How about this for a wacky way to do it:
var date = new Date(myStr.replace(
/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/,
'$4:$5:$6 $2/$3/$1'
));
Zero external libraries, one line of code ;-)
Explanation of the original method :
// EDIT: this doesn't work! see below.
var date = Date.apply(
null,
myStr.match(/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/).slice(1)
);
The match()
function (after it has been slice()
d to contain just the right) will return an array containing year, month, day, hour, minute, and seconds. This just happens to be the exact right order for the Date constructor. Function.apply
is a way to call a function with the arguments in an array, so I used Date.apply(<that array>)
.
for example:
var foo = function(a, b, c) { };
// the following two snippets are functionally equivalent
foo('A', 'B', 'C')
var arr = ['A', 'B', 'C'];
foo.apply(null, arr);
I've just now realised that this function doesn't actually work, since javascript months are zero-indexed. You could still do it in a similar method, but there'd be an intermediate step, subtracting one from the array before passing it to the constructor. I've left it here, since it was asked about in the comments.
The other option works as expected however.