Round a timestamp to the nearest date

前端 未结 7 1712
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:19

    function roundDownDate(date) {
      if (typeof date !== "object" || !date.getUTCMilliseconds) {
          throw Error("Arg must be a Date object.");
      }
      var offsetMs = date.getTimezoneOffset() * 60 * 1000,
          oneDayMs = 24 * 60 * 60 * 1000;
      return new Date(Math.floor((date.getTime() - offsetMs) / oneDayMs) * oneDayMs + offsetMs);
    };
    

    This should work and is pretty fast.

提交回复
热议问题