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
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());};