【问题标题】:Issues with the Date object when try to use getYear() and getDay() method [duplicate]尝试使用 getYear() 和 getDay() 方法时出现 Date 对象的问题 [重复]
【发布时间】:2021-07-26 13:57:07
【问题描述】:

我尝试使用 NodeJS v14.15.1 中的日期对象。当我使用年、月和日参数实例化对象时。当我尝试使用 getDay() 和 getYear() 方法时,我没有正确的数字。

我真的不知道发生了什么以及为什么这个方法没有返回我所期望的。

const date = new Date(2021, 4, 1) // I create a date object for 2021/04/01
console.log(date.getDay()) // This return 6 instead of 1
console.log(date.getYear()) // This return 121 instead if 2021

【问题讨论】:

  • RTMconst date = new Date(2021, 3, 1); console.log(date.getDay()); console.log(date.getfullYear())

标签: javascript node.js


【解决方案1】:

这里有一些不幸的历史命名方法。查看MDN's documentation for Date

  • getDay 返回星期几(星期日 = 0、星期一 = 1 等)。您可能想改用getDate

  • 同样,getYear 返回年份减去 1900。您可能希望改用 getFullYear

  • 虽然您没有提到它,但请注意 getMonth 从零开始:0 = 一月,1 = 二月等。new Date 也是如此。所以new Date(2021, 4, 1)对应ISO日期2021-05-01。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多