Moment JS start and end of given month

前端 未结 11 1468
无人及你
无人及你 2020-11-28 08:19

I need to calculate a JS date given year=2014 and month=9 (September 2014).

I tried this:

var moment = require(\'moment\');
var startDate = moment( y         


        
11条回答
  •  佛祖请我去吃肉
    2020-11-28 09:02

    const dates = getDatesFromDateRange("2014-05-02", "2018-05-12", "YYYY/MM/DD", 1);           
    console.log(dates);
    // you get the whole from-to date ranges as per parameters
    var onlyStartDates = dates.map(dateObj => dateObj["to"]);
    console.log(onlyStartDates);
    // moreover, if you want only from dates then you can grab by "map" function
    
    function getDatesFromDateRange( startDate, endDate, format, counter ) {
        startDate = moment(startDate, format);
        endDate = moment(endDate, format);
    
        let dates = [];
        let fromDate = startDate.clone();
        let toDate = fromDate.clone().add(counter, "month").startOf("month").add(-1, "day");
        do {
            dates.push({
                "from": fromDate.format(format),
                "to": ( toDate < endDate ) ? toDate.format(format) : endDate.format(format)
            });
            fromDate = moment(toDate, format).add(1, "day").clone();
            toDate = fromDate.clone().add(counter, "month").startOf("month").add(-1, "day");
        } while ( fromDate < endDate );
        return dates;
    }
    

    Please note, .clone() is essential in momentjs else it'll override the value. It seems in your case.

    It's more generic, to get bunch of dates that fall between dates.

提交回复
热议问题