简体   繁体   English

new Date()在不同环境中的行为不同,为什么?

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

when I define the same date in chrome, it shows the expected result. 当我在Chrome中定义相同的日期时,它会显示预期的结果。 but when I run it in node.js, the code is below: 但是当我在node.js中运行它时,代码如下:

 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 ? 我的问题是为什么不2015-02-01

It's timezone issue. 这是时区问题。 In Chrome, printed date and time is adjusted by your local timezone information. 在Chrome浏览器中,打印日期和时间会根据您当地的时区信息进行调整。 But date in Node.js you printed, its string format is ISO String with no adjustment timezone value. 但是在您打印的Node.js中的日期,它的字符串格式是ISO字符串,没有调整时区值。

So, both new Date(2015, 1, 1) have the same value in Chrome and Node.js. 因此,两个new Date(2015, 1, 1) 2015,1,1 new Date(2015, 1, 1)在Chrome和Node.js中具有相同的值。

Try console.log(date.toLocaleDateString()) . 尝试console.log(date.toLocaleDateString()) You would get 2015-2-1. 您会得到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 https://www.w3schools.com/js/js_date_formats.asp

Also, if your goal is having this format 2015-02-01 check https://momentjs.com/ . 另外,如果您的目标是使用2015-02-01这种格式,请查看https://momentjs.com/ For your case: 对于您的情况:

(Using moment.js) (使用moment.js)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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