将时间段按周分组

2019-11-26 15:15:07

阅读:184
分类:代码段

将时间段按周分组

使用moment.js 将时间段按周分组

    // node 测试
    const moment = require('moment')

    function initItem(arr, index) {
        arr[index] = { name: `第${index + 1}周`, days: [] }
        return arr
    }

    function calWeek(startTime, endTime) {
        moment.locale('fr', {
            week: {
                dow: 1 // Monday is the first day of the week.
            }
        })

        let startDay = moment(startTime)
        let endDay = moment(endTime)

        let index = 0
        let temp = []
        initItem(temp, index)

        while (!startDay.isAfter(endDay)) {
            if (startDay.days() === 1 && temp[index].days.length) {
                index++
                initItem(temp, index)
            }

            temp[index].days.push(startDay.format('YYYY-MM-DD'))

            startDay.add(1, 'd')
        }

        return temp
    }

    console.log(calWeek('2018-12-18', '2019-01-18'))

    /*
        输出
        [ { name: '第1周',
    days:
     [ '2018-12-18',
       '2018-12-19',
       '2018-12-20',
       '2018-12-21',
       '2018-12-22',
       '2018-12-23' ] },
  { name: '第2周',
    days:
     [ '2018-12-24',
       '2018-12-25',
       '2018-12-26',
       '2018-12-27',
       '2018-12-28',
       '2018-12-29',
       '2018-12-30' ] },
  { name: '第3周',
    days:
     [ '2018-12-31',
       '2019-01-01',
       '2019-01-02',
       '2019-01-03',
       '2019-01-04',
       '2019-01-05',
       '2019-01-06' ] },
  { name: '第4周',
    days:
     [ '2019-01-07',
       '2019-01-08',
       '2019-01-09',
       '2019-01-10',
       '2019-01-11',
       '2019-01-12',
       '2019-01-13' ] },
  { name: '第5周',
    days:
     [ '2019-01-14',
       '2019-01-15',
       '2019-01-16',
       '2019-01-17',
       '2019-01-18' ] } ]
    */

评论:

    X

    备案号 皖ICP备19021899号-1  技术支持 © 947968273@qq.com