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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27323791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:20:05  来源:igfitidea点击:

Round a timestamp to the nearest date

javascriptdatedatetimemomentjs

提问by daGUY

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

我需要按创建日期对我的 Web 应用程序中的一堆项目进行分组。

Each item has an exact timestamp, e.g. 1417628530199. I'm using Moment.jsand 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.

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

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 Agowith the first item underneath, then another header for 2 Days Agowith the second item underneath, etc.

问题是原始时间戳太具体了——在同一日期创建但相隔一分钟的两个项目每个都有一个唯一的时间戳。所以我得到了2 Days Ago第一个项目的标题,然后2 Days Ago是第二个项目的另一个标题,依此类推。

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?

将原始时间戳四舍五入到最近日期的最佳方法是什么,以便在同一日期创建的任何项目都具有完全相同的时间戳,从而可以组合在一起?

采纳答案by Joe L.

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/

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

回答by juvian

Well, using js you can do:

好吧,使用 js 你可以做到:

var d = new Date(1417628530199);
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);

Edit:

编辑:

After checking several methods, this one seems to be the faster:

检查了几种方法后,这个方法似乎更快:

function roundDate(timeStamp){
    timeStamp -= timeStamp % (24 * 60 * 60 * 1000);//subtract amount of time since midnight
    timeStamp += new Date().getTimezoneOffset() * 60 * 1000;//add on the timezone offset
    return new Date(timeStamp);
}

You can check difference in speed here: http://jsfiddle.net/juvian/3aqmhn2h/

您可以在这里查看速度差异:http: //jsfiddle.net/juvian/3aqmhn2h/

回答by Topher Fangio

Using Moment.js, you can use the following code to round everything to the beginning of the day:

使用 Moment.js,您可以使用以下代码将所有内容四舍五入到一天的开始:

moment().startOf('day').toString();
// -> Prints out "Fri Dec 05 2014 00:00:00 GMT-0800"

You can read more about startOf()in the docs.

您可以startOf()文档中阅读更多信息。

回答by Travis J

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 = new Date(Date.now() +43200000);
var rounded = new Date(offset .getFullYear(),offset .getMonth(),offset .getDate());
console.log(new Date());
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 “类”中也很有用。

Date.prototype.round = function(){
    var dateObj = new Date(+this+43200000);
    return new Date(dateObj.getFullYear(), dateObj.getMonth(), dateObj.getDate());
};
console.log(new Date().round());

Minimized:

最小化:

Date.prototype.round = function(){var d = new Date(+this+43200000);return new Date(d.getFullYear(), d.getMonth(), d.getDate());};

回答by Matt Budish

Here is a clean way to get just the date in one line with no dependencies:

这是一种在没有依赖项的情况下仅在一行中获取日期的干净方法:

let d = new Date().setHours(0, 0, 0, 0);

回答by norep

function roundDownDate(date) {
  if (typeof date !== "object" || !date.getUTCMilliseconds) {
      throw Error("Arg must be a Date object.");
  }
  var offsetMs = date.getTimezoneOffset() * 60 * 1000,
      oneDayMs = 24 * 60 * 60 * 1000;
  return new Date(Math.floor((date.getTime() - offsetMs) / oneDayMs) * oneDayMs + offsetMs);
};

This should work and is pretty fast.

这应该有效并且非常快。

回答by thomasttvo

function getDateOfTimeStamp(time) {
  var originTime = 0;
  var offsetOriginTime = originTime + new Date().getTimezoneOffset() * 60 * 1000;
  var timeSinceOrigin = time - offsetOriginTime;
  var timeModulo = timeSinceOrigin % (24 * 60 * 60 * 1000);
  var normalizedTime = time - timeModulo;

  console.log(new Date(normalizedTime) ,new Date(time));
  return normalizedTime;
}

This worked for my project. Pure math, no string manipulation needed, no external lib needed, so it's super fast.

这对我的项目有用。纯数学,不需要字符串操作,不需要外部库,所以它超级快。

You can try by copying the above function to javascript console and then do normalizeTimeToDate(Date.now())

您可以尝试将上述函数复制到 javascript 控制台,然后执行 normalizeTimeToDate(Date.now())