简体   繁体   English

使用Moment.js每月生成几天失败

[英]Generate days of a month using Moment.js fails

const generateDatesOfAMonth = () => {

    let start_date_of_month = moment().format("YYYY-MM-01"),
    end_date_of_month = moment().format("YYYY-MM-") + moment().daysInMonth(),
    dayArray = [];

    while (start_date_of_month <= end_date_of_month) {
        dayArray.push({ days: start_date_of_month });
        start_date_of_month = moment(start_date_of_month).add(1, 'days');
    }
    return dayArray;
}

What's wrong with my code above? 我上面的代码有什么问题? We can know number of days of each month, I found a solution via moment, but is my loop wrong? 我们可以知道每个月的天数,我很快就找到了解决方案,但是循环是否错误? I expect an array of days but what I got is only 1st day. 我希望有几天的时间,但是我只有第一天。 Hmm, any clue? 嗯,有什么线索吗?

I think start_date_of_month = moment(start_date_of_month).add(1, 'days'); 我认为start_date_of_month = moment(start_date_of_month).add(1, 'days');

should be start_date_of_month = start_date_of_month.add(1, 'days'); 应该是start_date_of_month = start_date_of_month.add(1, 'days');

Check out this resource: Format date and Subtract days using Moment.js 出此资源: 使用Moment.js格式化日期和减去日期

@AlenJenshen: Sorry, I do not have enough reputation to comment your question. @AlenJenshen:抱歉,我没有足够的声誉来评论您的问题。 But there are the solution for your question: 但是您的问题有解决方案:

const generateDatesOfAMonth = () => {

    let start_date_of_month = moment().format("YYYY-MM-01"),
    end_date_of_month = moment().format("YYYY-MM-") + moment().daysInMonth(),
    dayArray = [];


    while (start_date_of_month <= end_date_of_month) {
        dayArray.push({ days: start_date_of_month });
        start_date_of_month = moment(start_date_of_month).add(1, 'days').format("YYYY-MM-DD");
    }
    return dayArray;
}

You forgot to format start_date_of_month , so while loop can not compare start_date to end_date. 您忘记了设置start_date_of_month格式,因此while循环无法将start_date与end_date进行比较。 Please try my solution :) 请尝试我的解决方案:)

You can use [...Array(moment().daysInMonth()).keys()]; 您可以使用[...Array(moment().daysInMonth()).keys()]; to build and array with an element for each day of the month (eg [1, ... 31] ). 为每个月的每一天构建并排列一个元素(例如[1, ... 31] )。 Then you can use date() and format() to get your result. 然后,您可以使用date()format()获得结果。

Here a live working sample: 这是一个实时工作示例:

 const generateDatesOfAMonth = () => { // Get array of numbers for each day of the month let days = [...Array(moment().daysInMonth()).keys()]; // Create a moment object for each day and format it let dayArray = days.map( day => { return { days: moment().date(day+1).format('YYYY-MM-DD') } }); return dayArray; } console.log( generateDatesOfAMonth() ); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM