Round a timestamp to the nearest date

前端 未结 7 1731
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条回答
  •  萌比男神i
    2020-12-03 12:16

    Just construct a new Date from the existing one using only the year, month, and date. Add half a day to ensure that it is the closest date.

    var offset = new Date(Date.now() +43200000);
    var rounded = new Date(offset .getFullYear(),offset .getMonth(),offset .getDate());
    console.log(new Date());
    console.log(rounded);

    Since this seems to have a small footprint, it can also be useful to extend the prototype to include it in the Date "class".

    Date.prototype.round = function(){
        var dateObj = new Date(+this+43200000);
        return new Date(dateObj.getFullYear(), dateObj.getMonth(), dateObj.getDate());
    };
    console.log(new Date().round());

    Minimized:

    Date.prototype.round = function(){var d = new Date(+this+43200000);return new Date(d.getFullYear(), d.getMonth(), d.getDate());};
    

提交回复
热议问题