【问题标题】:Converting date string to Date() adds a month [duplicate]将日期字符串转换为 Date() 会增加一个月 [重复]
【发布时间】:2020-12-09 20:36:29
【问题描述】:

好的,我有一个奇怪的问题。我刚开始使用 Node 和 MongoDB,起初我对整个 ISO 时间与本地时间有点混淆,我遇到了一个奇怪的问题。

我得到了一个带日期的字符串,虽然它有点矫枉过正,但我​​手动将其拆分并传递给“new Date()”构造函数,它会将所有日期添加一个月。

这是我的代码:

str = str.split(' ')
str[0] = str[0].split('-')
str[1] = str[1].split(':')
console.log(str)
str = new Date(str[0][0],str[0][1],str[0][2],str[1][0],str[1][1],str[1][2]);
console.log(str)
console.log(str.toString())

这是输出:

[ [ '1970', '01', '01' ], [ '00', '00', '00' ] ]  //First UNIX date splitted into a yyyy, mm, dd, HH, MM, DD
1970-02-01T03:00:00.000Z                          //After the Date object is generated, note that the month is now "02"
Sun Feb 01 1970 00:00:00 GMT-0300 (hora de verano de Chile) //The date returned to local time. Note that the month change was maintained.

我在更改类型时做错了吗?是不是和代码无关?

整个目的是将Date对象插入到ISO格式的mongodb集合中,然后查询回来,并以当地时间显示。

【问题讨论】:

  • Date 类的月份从零开始。一月是0。因此,如果您在 1 的一个月内通过,您就是在告诉日期是 2 月。

标签: javascript node.js mongodb datetime


【解决方案1】:

根据the documentationDate,月份是零索引的。所以它不是添加一个月,你只是传递了错误的值,因为你的字符串中的月份是单索引的。

从该值中减去1

new Date(str[0][0], str[0][1] - 1, str[0][2], str[1][0], str[1][1], str[1][2]);

【讨论】:

  • 哇,虽然我错过了查看日期文档(新手错误),但我很惊讶我无法通过直接在谷歌上搜索找到答案。谢谢!
猜你喜欢
  • 2020-08-26
  • 2014-12-08
  • 2014-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-17
  • 2016-12-24
  • 2012-07-30
相关资源
最近更新 更多