将时间戳舍入到最近的日期

编程入门 行业动态 更新时间:2024-10-24 22:22:04
本文介绍了将时间戳舍入到最近的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

jsfiddle/cdn5rvck/4/

更多推荐

将时间戳舍入到最近的日期

本文发布于:2023-10-16 05:26:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1496633.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日期   时间   戳舍入到

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!