Round A Timestamp To The Nearest Date
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 'time from now' feature to convert
Solution 1:
Well, using js you can do:
var d = newDate(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);
Solution 2:
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.
Solution 3:
Here is a clean way to get just the date in one line with no dependencies:
let d = newDate().setHours(0, 0, 0, 0);
Solution 4:
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 = newDate(Date.now() +43200000);
var rounded = newDate(offset .getFullYear(),offset .getMonth(),offset .getDate());
console.log(newDate());
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 = newDate(+this+43200000);
returnnewDate(dateObj.getFullYear(), dateObj.getMonth(), dateObj.getDate());
};
console.log(newDate().round());
Minimized:
Date.prototype.round = function(){var d = newDate(+this+43200000);returnnewDate(d.getFullYear(), d.getMonth(), d.getDate());};
Solution 5:
Try this:
Date.prototype.formatDate = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString();
var dd = this.getDate().toString();
return yyyy + (mm[1]?mm:"0"+mm[0]) + (dd[1]?dd:"0"+dd[0]);
};
var utcSeconds = 1417903843000,
d = newDate(0);
d.setUTCSeconds(Math.round( utcSeconds / 1000.0));
var myTime = (function(){
var theTime = moment(d.formatDate(), 'YYYYMMDD').startOf('day').fromNow();
if(theTime.match('hours ago')){
return'Today';
}
return theTime;
})();
alert( myTime );
Post a Comment for "Round A Timestamp To The Nearest Date"