Converting a string formatted YYYYMMDDHHMMSS into a JavaScript Date object

16,423

Solution 1

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.

Solution 2

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.

Solution 3

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");

Solution 4

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

Share:
16,423
Admin
Author by

Admin

Updated on July 06, 2022

Comments

  • Admin
    Admin almost 2 years

    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!