将时间戳舍入到最近的日期 [英] Round a timestamp to the nearest date

查看:147
本文介绍了将时间戳舍入到最近的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要按照创建的日期在我的网络应用程序中分组一些项目。

I need to group a bunch of items in my web app by date created.

每个项目都有一个确切的时间戳,例如 1417628530199 。我正在使用 Moment.js 及其从现在起的时间功能将这些原始时间戳转换为可读取的日期,例如 2天前。然后我想使用可读日期作为在同一天创建的一组项目的标题。

Each item has an exact timestamp, e.g. 1417628530199. 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.

问题是原始时间戳太具体 - 两个项目它们在相同的日期创建,但是相隔一分钟,每个都有一个唯一的时间戳。所以我得到一个标题为 2天前与下面的第一个项目,然后另一个标题为 2天前

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?

推荐答案

尝试这样:

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/

这篇关于将时间戳舍入到最近的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆