【问题标题】:JS UTC timestamp behaviourJS UTC 时间戳行为
【发布时间】:2020-12-01 02:08:58
【问题描述】:

我对这种时间转换的工作方式感到困惑。我有时间戳 1462060800000,当我正确上交日期时,它变成: 2016 年 5 月 1 日星期日 02:00:00 GMT+0200(中欧夏令时间)

但是当我想用 const startMonth = start.getUTCMonth() 获得月份时,我得到的是 4 而不是 5。为什么会发生这种情况,我需要做什么才能获得正确的月份?

const timestamp = 1462060800000
const start = new Date(timestamp)
console.log(start) // Sun May 01 2016 02:00:00 GMT+0200 (Central European Summer Time)

const startYear = start.getUTCFullYear()
const startMonth = start.getUTCMonth()
console.log(startMonth) // 4

【问题讨论】:

标签: javascript


【解决方案1】:

getUTCMonth() 返回从零开始的月份。 4 是正确的。见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCMonth

【讨论】:

  • 是的,我刚刚意识到这一点。谢谢
【解决方案2】:

我知道它实际上是一个以 0 开头的月份索引。

【讨论】:

    【解决方案3】:

    getUTCMonth() 根据世界时返回指定日期的月份,作为从零开始的值(其中零表示一年中的第一个月)

    从文档中看到Date.prototype.getUTCMonth()

    【讨论】:

      【解决方案4】:

      getUTCMonth() 方法与 getMonth() 一样,计数为零 (0)。这意味着该时期将是这样的 - 0 and 11。要获取所需月份,您需要添加+1

      const startMonth = start.getUTCMonth() + 1;
      

      Loot it.

      const timestamp = 1462060800000;
      const start = new Date(timestamp);
      console.log(start); // Sun May 01 2016 02:00:00 GMT+0200 (Central European Summer Time)
      
      const startYear = start.getUTCFullYear();
      const startMonth = start.getUTCMonth() + 1;
      console.log(startMonth);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-15
        • 2017-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多