代码之家  ›  专栏  ›  技术社区  ›  LP13

为什么javascript返回从零开始的日期?

  •  0
  • LP13  · 技术社区  · 5 年前

    我知道javascript getMonth() 该方法以从零开始的值返回月份(其中零表示一年的第一个月)

    getDate()方法也是从零开始的日期吗?(不是根据 documentation )

    但是,当我将YYYY-MM-DD格式的字符串传递给日期构造器时,getDate()返回从零开始的日期。

    var d = new Date("2020-06-15");
    console.log(getDatePartAsString(d));
    
    function getDatePartAsString(d)
    {
      if (!isValid(d)) {
          return "";
      }
    
      var dt = new Date(d);
      return dt.getMonth() + 1 + "/" + dt.getDate() + "/" + dt.getFullYear();
    }
    
    function isValid(d)
    {
      return !isNaN(new Date(d).getTime());
    }

    更新1
    enter image description here

    1 回复  |  直到 5 年前
        1
  •  2
  •   CertainPerformance    5 年前

    该方法将 return :

    一个介于1和31之间的整数,表示给定日期的月份中的第几天 根据当地时间 .

    问题不在于该方法是0索引的——问题在于你的本地时区把事情搞砸了。使用 getUTCDate 相反,返回的日期号是世界时(或与您传递给date构造函数的时区相对应):

    var d = new Date("2020-06-15");
    console.log("Day " + d.getUTCDate());