javascript - 如何在 MomentJS 中获取上个月、过去三个月的天数列表
问题描述
使用moment().subtract(1, 'days').format("YYYY-MM-DD")
i 可以获得当前日期的最后 x 天。那么我怎样才能得到上个月或过去三个月的所有天数..?
解决方案
这是获取当月天数的方法:
const numberOfDaysInCurrentMonth = moment().daysInMonth();
因此,您可以通过以下方式获取上个月的天数:
const numberOfDaysInLastMonth = moment().subtract(1, 'months').daysInMonth();
现在你需要上个月的开始:
const startOfLastMonth = moment().subtract(1, 'months').startOf('month');
您已准备好开始迭代并构建您的列表:
const numberOfDaysInLastMonth = moment().subtract(1, 'months').daysInMonth();
const startOfLastMonth = moment().subtract(1, 'months').startOf('month');
for (let i = 0; i < numberOfDaysInLastMonth; i = i + 1) {
console.log(startOfLastMonth.format('YYYY MMM DD'));
startOfLastMonth.add(1, 'days');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
对于过去 3 个月,只需更改您的开始日期和天数:
const numberOfDaysInLast3Months = moment().subtract(1, 'months').daysInMonth() +
moment().subtract(2, 'months').daysInMonth() +
moment().subtract(3, 'months').daysInMonth();
const startDate = moment().subtract(3, 'months').startOf('month');
for (let i = 0; i < numberOfDaysInLast3Months; i = i + 1) {
console.log(startDate.format('YYYY MMM DD'));
startDate.add(1, 'days');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
推荐阅读
- docker - 如何从主机(Windows 机器)连接到 docker 容器
- log4j - 如何为嵌入式 Jetty 服务器配置 log4j.properties?
- ruby-on-rails - 通过 Rmagick 错误将 PDF/DOC/DOX 转换为 PNG 时:没有这样的文件或目录 @error/blob.c/OpenBlob/2712 - Ruby on Rails
- sql - 如何修改我的模式或查询,使其有效运行?
- swiftui - SwiftUI iOS 14 beta TextField 100% CPU
- mysql - AWS lambda 执行中的数据库错误“无法连接到 MySQL 服务器”
- typescript - 传递任何或记录时,TypeScript 中重载匹配顺序的函数签名
- node.js - 用大量数据解决 promise 时阻塞的事件循环
- reactjs - 面临加载资源失败:将我的反应应用程序上传到 github 页面时,服务器响应状态为 404 ()
- hsm - 配置 Safenet Luna EFT HSM 以允许 ISO-0 到 ISO-1 引脚转换