Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a string formatted YYYYMMDDHHMMSS into a JavaScript Date object

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 advance!

like image 408
John Jones Avatar asked Dec 02 '09 16:12

John Jones


4 Answers

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.

like image 193
nickf Avatar answered Nov 10 '22 07:11

nickf


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.

like image 40
Christoph Avatar answered Nov 10 '22 09:11

Christoph


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");
like image 3
Daff Avatar answered Nov 10 '22 07:11

Daff


If you can use jQuery, jQuery.ui.datepicker has a utility function.

like image 1
kgiannakakis Avatar answered Nov 10 '22 08:11

kgiannakakis