gpt4 book ai didi

javascript - JS : Get all months from specific date until today (also using moment. js)

转载 作者:行者123 更新时间:2023-11-28 20:13:42 25 4
gpt4 key购买 nike

假设我有一个特定日期,例如:21-03-2013,并且我想获取我使用的月份:moment("04-03-2013","DD-MM-YYYY").format('MMMM'); 这给了我三月。

现在对于今天的日期,我使用 moment().format('MM'); 这给了我十月。

如何获取名称中的所有月份?

最佳答案

如果有必要,这也适用于更长的时间(> 1 年)

function getDates(startDate /*moment.js date object*/) {
nowNormalized = moment().startOf("month"), /* the first of current month */
startDateNormalized = startDate.clone().startOf("month").add("M", 1), /* the first of startDate + 1 Month - as it was asked for the months in between startDate and now */
months = [];

/* .isBefore() as it was asked for the months in between startDate and now */
while (startDateNormalized.isBefore(nowNormalized)) {
months.push(startDateNormalized.format("MMMM"));
startDateNormalized.add("M", 1);
}

return months;
}

fiddle

更新
正如马特在评论中建议的那样,我现在使用 .clone().startOf("month")而不是自己创建标准化克隆

关于javascript - JS : Get all months from specific date until today (also using moment. js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19509389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com