Round a timestamp to the nearest date

前端 未结 7 1714
Happy的楠姐
Happy的楠姐 2020-12-03 11:23

I need to group a bunch of items in my web app by date created.

Each item has an exact timestamp, e.g. 1417628530199. I\'m using Moment.js and its \"tim

相关标签:
7条回答
  • 2020-12-03 12:21
    function getDateOfTimeStamp(time) {
      var originTime = 0;
      var offsetOriginTime = originTime + new Date().getTimezoneOffset() * 60 * 1000;
      var timeSinceOrigin = time - offsetOriginTime;
      var timeModulo = timeSinceOrigin % (24 * 60 * 60 * 1000);
      var normalizedTime = time - timeModulo;
    
      console.log(new Date(normalizedTime) ,new Date(time));
      return normalizedTime;
    }
    

    This worked for my project. Pure math, no string manipulation needed, no external lib needed, so it's super fast.

    You can try by copying the above function to javascript console and then do normalizeTimeToDate(Date.now())

    0 讨论(0)
提交回复
热议问题