日历,按周分隔的天数列表

时间:2016-12-19 14:29:22

标签: javascript

如何在纯Javascript中生成按周分组的列表/数组天数?就像邮件日历中的“周” - 显示

这应该是最终输出

<ul>
  ...
  <li id="currrentWeek" data-week-nr="51">
    <div class="today" data-day="1" data-dayOfMonth="19">monday</div>
    <div data-day="2" data-dayOfMonth="20">tuesday</div>
    <div data-day="3" data-dayOfMonth="21">wednesday</div>
    <div data-day="4" data-dayOfMonth="22">thursday</div>
    <div data-day="5" data-dayOfMonth="23">friday</div>
    <div data-day="6" data-dayOfMonth="24">saturday</div>
    <div data-day="0" data-dayOfMonth="25">sunday</div>
  </li>
  <li id="nextWeek" data-week-nr="52">
    <div data-day="1" data-dayOfMonth="26">monday</div>
    <div data-day="2" data-dayOfMonth="27">tuesday</div>
    <div data-day="3" data-dayOfMonth="28">wednesday</div>
    <div data-day="4" data-dayOfMonth="29">thursday</div>
    <div data-day="5" data-dayOfMonth="30">friday</div>
    <div data-day="6" data-dayOfMonth="31">saturday</div>
    <div data-day="0" data-dayOfMonth="01">sunday</div>
  </li>
  ...
</ul>

谢谢

1 个答案:

答案 0 :(得分:0)

哦,很酷,我刚刚在上周写了(稍微)丑陋的代码:

// let's start with a function that gives us all weeks in a range
function* weeks(from, to = new Date()) {
  for (var f = from.getTime(); f <= to; f += 1000 * 60 * 60 * 24 * 7) {
    let d = new Date(f);
    while (d.getDay() === 0 || d.getDay() === 6) {
      d = new Date(d.getTime() + 1000 * 60 * 60 * 24);
     }
     yield d;
  }
}

找到最早日期的助手:

 function earliestDate(dates) {
      return dates.sort((x, y) => y - x).pop();
 }

现在,让我们检查几天内的哪些天数

 function* groupByWeek(dates) {
   for(const week of weeks(earliestDate(dates))) {
     const fromWeek = dates.filter(x => x < week); 
     dates = dates.filter(x => !fromWeek.includes(x));
     yield dates; 
   }
 }

您可以使用Array.from将其作为数组返回。