daGUY daGUY - 1 year ago 100
Javascript Question

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.

. I'm using Moment.js and its "time from now" feature to convert these raw timestamps into nice readable dates, e.g.
2 Days Ago
. I then want to use the readable date as a header for a group of items created on the same date.

The problem is that the raw timestamps are too specific - two items that are created on the same date but a minute apart will each have a unique timestamp. So I get a header for
2 Days Ago
with the first item underneath, then another header for
2 Days Ago
with the second item underneath, etc.

What's the best way to round the raw timestamps to the nearest date, so that any items created on the same date will have the exact same timestamp and thus can be grouped together?

Answer Source

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 = new Date(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 );


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download