首页 > 解决方案 > 从两种不同的日期方法获取毫秒

问题描述

为什么这两种获取毫秒的方式有区别

gigasecond = inputDate => {
  console.log(inputDate)
  console.log(inputDate.getTime())     //1303689600000
  console.log(
    Date.UTC(inputDate.getFullYear(), 
             inputDate.getMonth(),
             inputDate.getDate(),
             inputDate.getHours(), 
             inputDate.getMinutes(),
             inputDate.getSeconds())); //1303709400000
};

gigasecond(new Date(Date.UTC(2011, 3, 25)))

标签: javascriptdategettime

解决方案


getHours()方法根据本地时间返回指定日期的小时。改为使用getUTCHours()

gigasecond = inputDate => {
  console.log(inputDate)
  console.log(inputDate.getHours(), inputDate.getUTCHours())
  console.log(inputDate.getTime()) //1303689600000
  console.log(
    Date.UTC(inputDate.getFullYear(),
      inputDate.getUTCMonth(),
      inputDate.getUTCDate(),
      inputDate.getUTCHours(),
      inputDate.getUTCMinutes(),
      inputDate.getUTCSeconds()
    )
  ); //1303709400000
};

gigasecond(new Date(Date.UTC(2011, 3, 25)))


推荐阅读