Search code examples
javascriptdategettime

Getting milliseconds from two different methods of date


Why there is the difference between these two ways of getting milliseconds

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)))


Solution

  • The getHours() method returns the hour for the specified date, according to local time. Use getUTCHours() instead.

    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)))