Moment.js - Get all mondays between a date range

后端 未结 1 1889
耶瑟儿~
耶瑟儿~ 2021-01-18 02:54

I have a date range that looks like this

let start = moment(this.absence.FromDate);
let end = moment(this.absence.ToDate);

The user can dec

1条回答
  •  伪装坚强ぢ
    2021-01-18 03:16

    You can get next Monday using .day(1) and then loop until your date isBefore your end date adding 7 days for each iteration using add

    Here a live sample:

    //let start = moment(this.absence.FromDate);
    //let end = moment(this.absence.ToDate);
    
    // Test values
    let start = moment();
    let end = moment().add(45 , 'd');
    
    var arr = [];
    // Get "next" monday
    let tmp = start.clone().day(1);
    if( tmp.isAfter(start, 'd') ){
      arr.push(tmp.format('YYYY-MM-DD'));
    }
    while( tmp.isBefore(end) ){
      tmp.add(7, 'days');
      arr.push(tmp.format('YYYY-MM-DD'));
    }
    console.log(arr);

    0 讨论(0)
提交回复
热议问题