Angularjs 1:按周排序日期

时间:2017-09-18 15:00:19

标签: javascript angularjs date

我有objs列表:

[{
   name: one,
   date: 2017-09-18
}, {
   name: two,
   date: 2017-09-11
}, {
   name: three,
   date: 2017-09-13
}]

我希望按周排序。 也许像:

{
1week(or , maybe better key like start of week): [{
       name: two,
       date: 2017-09-11
    }, {
       name: three,
       date: 2017-09-13
    ],
2week: [{
       name: one,
       date: 2017-09-18
    }]
}

如何确定日期属于哪一周? 我怎么能做得更好?

1 个答案:

答案 0 :(得分:1)

我玩弄了这个,我认为这与你需要的相似:

https://jsfiddle.net/pegla/ytmayemr/

代码:

let arrayOfDates = [{
   name: 'one',
   date: '2017-09-18'
}, {
   name: 'two',
   date: '2017-09-11'
}, {
   name: 'three',
   date: '2017-09-13'
}];

function getWeekNumber(d) {
    // Copy date so don't modify original
    d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
    // Set to nearest Thursday: current date + 4 - current day number
    // Make Sunday's day number 7
    d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay()||7));
    // Get first day of year
    var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
    // Calculate full weeks to nearest Thursday
    var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7);
    // Return array of year and week number
    return [d.getUTCFullYear(), weekNo];
}

let newArrayOfDatesByWeek = arrayOfDates.reduce((prevVal, currVal, index)=>{
    let week = `week ${getWeekNumber(new Date(currVal.date))[1]} of ${getWeekNumber(new Date(currVal.date))[0]}`;
  if(!(week in prevVal)) {
    prevVal[week] = []; 
  }
  prevVal[week].push(currVal);
  return prevVal;
}, []);

console.log(newArrayOfDatesByWeek);

getWeekNumber函数取自RobG的这个答案,所以谢谢你: Get week of year in JavaScript like in PHP