简体   繁体   中英

new Date() behaves differently in different environment, why?

when I define the same date in chrome, it shows the expected result. but when I run it in node.js, the code is below:

 var date = new Date(2015, 1, 1); console.log(date); // it displays: 2015-01-31T16:00:00.000Z 

My question is why not 2015-02-01 ?

It's timezone issue. In Chrome, printed date and time is adjusted by your local timezone information. But date in Node.js you printed, its string format is ISO String with no adjustment timezone value.

So, both new Date(2015, 1, 1) have the same value in Chrome and Node.js.

Try console.log(date.toLocaleDateString()) . You would get 2015-2-1.

You're just printing the date object

var date = new Date(2015, 1, 1)
console.log(date); 

For more in-depth explanation check:

https://www.w3schools.com/js/js_date_formats.asp

Also, if your goal is having this format 2015-02-01 check https://momentjs.com/ . For your case:

(Using moment.js)

moment(new Date(2015, 1, 1)).format('YYYY-MM-DD') // "2015-02-01"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM