Round a timestamp to the nearest date

前端 未结 7 1716
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条回答
  •  时光取名叫无心
    2020-12-03 12:18

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

    http://jsfiddle.net/cdn5rvck/4/

提交回复
热议问题