Why does this date turn into a day earlier when the new date () is used?

Given date 2016-02-04. Suppose it will be February 4th, 2016. But when I use it new Date(), it returns as Wed Feb 03 2016 16:00:00 GMT-0800 (PST), rather than Thu Feb 04....

Below I literally do everything:

var _entryDate = new Date("2016-02-04");
console.log(_entryDate); // Wed Feb 03 2016 16:00:00 GMT-0800 (PST)

Why is this happening and how do I get the desired result, which is February 4, and not the day before?

+4
source share
4 answers

var dateArray = "2016-02-04".split("-");
var year = dateArray[0];
var month = parseInt(dateArray[1], 10) - 1;
var date = dateArray[2];
var _entryDate = new Date(year, month, date);
alert(_entryDate);
Run codeHide result

Removed unnecessary parseIntfor monthand yearas suggested by @RobG

, Pointy ( ). , UTC . , Date Date, , . , Date .

+2

, , UTC, . 8 .

, T00:00-0800 . , Date , .

+5

Javascript Date . , .

: ? , ECMAScript; . Universal Time - , .

, , Javascript . , , US/Eastern ( "EST" ):

new Date('2016-02-04')
//=> Wed Feb 03 2016 19:00:00 GMT-0500 (EST)  - midnight UTC
new Date(2016,2,4)
//=> Fri Mar 04 2016 00:00:00 GMT-0500 (EST)  - midnight EST

:

new Date('2016-02-04T00:00:00-05:00')

, . , , , .

+2
source

This is because the date is stored (and parsed) in UTC, but displayed in your local time zone. To display the correct date, you can use

new Date("2016-02-04").toISOString()
+1
source

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


All Articles