javascript - 两个日期之间存在的所有月份的列表,包括日期之间的差异小于 30 天的情况
问题描述
我想获取 JS 中两个日期之间存在的所有月份的列表。例如:
'2021-04-25' 到 '2021-05-12' 应该返回 [4,5]// case when num difference between dates is less than 30 days
'2021-04-25' 到 '2021-08-12' 应该返回 [4,5,6,7,8]
'2021-10-25' 到 '2022-02-12' 应该返回 [10,11,12,1,2]
以下代码有效,但没有给出“2021-04-25”到“2021-05-12”的正确结果。它只返回 [4]
我在这里尝试了示例JavaScript:获取两个日期之间的所有月份?但是如果天数 <30,momentjs 不会给出 endMonth
解决方案
我认为这是获得您正在寻找的结果的好解决方案
function getMonths(start, end) {
start = moment(start).startOf('month');
end = moment(end).startOf('month');
if (start.isAfter(end))[start, end] = [end, start]; // This is only for order the dates
const months = [];
while (start.isSameOrBefore(end)) {
months.push(start.month() + 1);
start.add(1, 'months');
}
return months;
}
console.log(getMonths('2021-04-25', '2021-05-12'));
console.log(getMonths('2021-04-25', '2021-08-12'));
console.log(getMonths('2021-10-25', '2022-02-12'));
console.log(getMonths('2021-04-25', '2022-02-12'));
console.log(getMonths('2021-06-26', '2020-02-12'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
推荐阅读
- jquery - 如何使用节点接收 ajaxed 多部分表单数据
- python - 将 fit 文件转换为 healpix 地图
- oracle - 如何让用户在 Oracle 实时服务器的 PlSql 中输入值?
- logging - 即使日志文件中有错误,Nagios check_logs.pl 也会给出 OK
- javascript - Javascript:单参数 Array.map() 的不同行为取决于我是否使用花括号(不是两种形式都允许吗?)
- android - 无法在片段中获得幻灯片效果
- macos - hidd 进程在控制台中生成错误消息
- amazon-web-services - 已解决___使用 AWS S3 到 Webhost 没有给出关键错误
- node.js - Node.js 中的阻塞事件循环仍然存在问题吗?
- python - 我正在尝试在 Pycharm 中使用 Selenium webdriver,您可以在您的项目中使用它还是仅在 Python 控制台中使用它?