How to group objects with timestamps properties by day, week, month?
javascript, node.js, timestamp, timezone
Solution
Here is my solution. Keep in mind that day, week and month are relative to origin, since epoch:
let event = [ {id: 1, date: 1387271989749 }, {id:2, date: 1387271989760} ];
function groupday(value, index, array){
let byday={};
let d = new Date(value['date']);
d = Math.floor(d.getTime()/(1000*60*60*24));
byday[d]=byday[d]||[];
byday[d].push(value);
return byday
}
function groupweek(value, index, array){
let byweek={};
let d = new Date(value['date']);
d = Math.floor(d.getTime()/(1000*60*60*24*7));
byweek[d]=byweek[d]||[];
byweek[d].push(value);
return byweek
}
function groupmonth(value, index, array){
let bymonth={};
d = new Date(value['date']);
d = (d.getFullYear()-1970)*12 + d.getMonth();
bymonth[d]=bymonth[d]||[];
bymonth[d].push(value);
return bymonth
}
console.log('grouped by day', event.map(groupday));
console.log('grouped by week',event.map(groupweek));
console.log('grouped by month',event.map(groupmonth));
NOTE: Objects are grouped but the keys for day, week and month are in digits. Only the key for year is human readable.
Problem
In a nodejs application, I have an array of event objects formatted as follows: ``` eventsArray = [ {id: 1, date: 1387271989749 }, {id:2, date: 1387271989760}, ... ] ``` 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: { ... } } ``` 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.