如何按天,周,月分组具有时间戳属性的对象? [英] How to group objects with timestamps properties by day, week, month?

查看:128
本文介绍了如何按天,周,月分组具有时间戳属性的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在nodejs应用程序中,我有一个事件对象数组,格式如下:

In a nodejs application, I have an array of event objects formatted as follows:

eventsArray = [ {id: 1, date: 1387271989749 }, {id:2, date: 1387271989760}, ... ]

eventsArray具有可变长度的n个元素,假设我选择时间参考为巴黎时间,我希望能够按天,周或月分组元素:

eventsArray having a variable length of n elements, and supposing I choose time reference to be Paris time, I want to be able to group elements by day, week, or month:

groupedByDay = {

            2012: { ... },
            2013: {
              dayN  : [{id: a0, date: b0}, {id: a1, date: b1}, {id: a2, date: b2 }],
              dayN+1: [{id: a3, date: b3}, {id: a4, date: b4}, {id: a5, date: b5 }],
              ...
                   },
            2014: { ... }

          }

groupedByWeek = {
            2012: { ... }
            2013: {
              weekN: [{id: a0, date: b0}, {id: a1, date: b1}, {id: a2, date: b2 }],
              weekN+1: [{id: a3, date: b3}],
              ....
                  },
             2014: { ... }
                }

groupedByMonth = {
             2012: { ... },
             2013: {
               monthN: [ {id: a0, date: b0 }, {id: a1, b1}, {id: a2, b2}, {id: a3, b3 }],
               monthN+1: [ {id: a4, date: b4 }, {id: a5, b5}, {id: a6, b6}],
               ...
                   },
              2014: { ... }
                 }

在操作unix时间戳方面经验很少,我想知道如何做到这一点,或者是否有一个npm模块可以使这更容易。

Having very little experience with manipulating unix timestamps, I was wondering how this could be done or if there was an npm module that would make this easier.

推荐答案

这是我的解决方案。请记住,日期,周和月相对于原点,因为纪元:

Here is my solution. Keep in mind that day, week and month are relative to origin, since epoch:

eventsArray = [ {id: 1, date: 1387271989749 }, {id:2, date: 1387271989760} ];
byday={};
byweek={};
bymonth={};
function groupday(value, index, array)
{
    d = new Date(value['date']);
    d = Math.floor(d.getTime()/(1000*60*60*24));
    byday[d]=byday[d]||[];
    byday[d].push(value);
}
function groupweek(value, index, array)
{
    d = new Date(value['date']);
    d = Math.floor(d.getTime()/(1000*60*60*24*7));
    byweek[d]=byweek[d]||[];
    byweek[d].push(value);
}
function groupmonth(value, index, array)
{
    d = new Date(value['date']);
    d = (d.getFullYear()-1970)*12 + d.getMonth();
    bymonth[d]=bymonth[d]||[];
    bymonth[d].push(value);
}
eventsArray.map(groupday);
eventsArray.map(groupweek);
eventsArray.map(groupmonth);

这篇关于如何按天,周,月分组具有时间戳属性的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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