Round a timestamp to the nearest date
Here is a clean way to get just the date in one line with no dependencies:
let d = new Date().setHours(0, 0, 0, 0);
Well, using js you can do:
var d = new Date(1417628530199);
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
A shorter way of writing it is d.setHours(0, 0, 0, 0);
Using Moment.js, you can use the following code to round everything to the beginning of the day:
moment().startOf('day').toString();
// -> Prints out "Fri Dec 05 2014 00:00:00 GMT-0800"
You can read more about startOf()
in the docs.
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());};