Convert string in YYYYMMDDHHMMSS format to a JavaScript Date object

I have a string with a date in it, formatted like this: YYYYMMDDHHMMSS. I was wondering how I would convert it to a JavaScript Date object with JavaScript.

Thanks in advance!

+3
source share
6 answers

How about this for a wacky way to do this:

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

match() ( , slice() d, ) , , , , , ​​. Date. Function.apply - , Date.apply(<that array>).

:

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

, , javascript . , , , . , .

.

+7

:

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

: Date() .

+4

DateJS , , JavaScript. , :

Date.parseExact("20091202051200", "YYYYMMDDHHMMSS");
+3

jQuery, jQuery.ui.datepicker .

+1
0

Your line does not have time zone information. Most likely GMT, so this should be taken into account when you make a date. You can easily perform the conversion using 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)
*/
0
source

Source: https://habr.com/ru/post/1724507/


All Articles