How to create a Date object from a string date in Javascript for the first years of AD?


I have the following date string:

"Thu Nov 14 0002 01:01:00 GMT + 0200 (standard GTB time)"

and I'm trying to convert it to a Date object:

date = new Date("Thu Nov 14 0002 01:01:00 GMT+0200 (GTB Standard Time)")  
=> Invalid Date {}

and it does not work. AND

date = new Date("Thu Nov 14 2 01:01:00 GMT+0200 (GTB Standard Time)")  
=> Invalid Date {}

doesn't work either

but

date = new Date("Thu Nov 14 2002 01:01:00 GMT+0200 (GTB Standard Time)")

work

Does anyone know an elegant way to take it apart?

+3
source share
2 answers

You can set any date. Including minutes, hours, and milliseconds, directly using a timestamp, dates before 1970 are negative integers.

alert(new Date(-62076675540000).toUTCString());

// >> Wed, 13 Nov 0002 23:01:00 GMT

Or you can set the date as a string by replacing the years to make it over 1000,
then subtracting the amount you added  with setFullYear()

var d=new Date("Thu Nov 14 1002 01:01:00 GMT+0200 (GTB Standard Time)")
d.setFullYear(d.getFullYear()-1000)
alert(d.toUTCString())

// >> Wed, 13 Nov 0002 23:01:00 GMT

You can automate a conversion to timestamps-

var s="Thu Nov 14 0002 01:01:00 GMT+0200 (GTB Standard Time)";
var y=s.split(' ')[3], y2=5000+(+y);
var d=new Date(s.replace(y,y2));
d.setFullYear(d.getFullYear()-5000)
var timestamp=+d;
alert(timestamp)
// >> -62076675540000
+6
source

Javascript 1 1970 , 00: 00: 00.000 UTC. .

.

edit — , Javascript, , ; , 32- . , , , . , .

(, , ) , Chrome Firefox 100 20- .

— Mozilla, -100 000 000 100 000 000 .

+3

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


All Articles