[英]Get list of start and end of months between 2 dates with moment JS
I have 2 dates like this 我有两个这样的约会
2018-01-01
and 2019-01-01
2018-01-01
和2019-01-01
I want to return a list of all months between those 2 dates but get both the start of the month and the end in the list like this 我想返回这两个日期之间所有月份的列表,但是像这样在列表中同时获得月份的开始和结束
2018-01-01 - 2018-01-31
2018-02-01 - 2018-02-28
2018-03-01 - 2018-03-31
and so on for all months between the 2 dates. 以此类推,直到两个日期之间的所有月份都如此。 How would I do this with Moment JS? 如何使用Moment JS做到这一点?
Just a small runnable sample. 只是一个小的可运行样本。 Be careful with moment.js: moments mutate! 小心moment.js:瞬间发生变化!
I hope this will help you! 我希望这能帮到您!
const format = 'YYYY-MM-DD'; const start = moment('2018-01-01', format), end = moment('2019-01-01', format); const result = []; while(start.isBefore(end)) { result.push({ start: start.startOf('month').format(format), end: start.endOf('month').format(format) }); start.add(1, 'month'); } console.log(result);
<script src="https://momentjs.com/downloads/moment.min.js"></script>
I'd go with something like this: 我会选择这样的东西:
var start = moment('2018-01-01', 'YYYY-MM-DD')
var end = moment('2019-01-01', 'YYYY-MM-DD')
while (start < end) {
console.log(start.startOf('month').format('YYYY-MM-DD'))
console.log(start.endOf('month').format('YYYY-MM-DD'))
start.add(1, 'month')
}
As other users have pointed out moment
's objects mutate when you use methods like startOf
and endOf
, so you should consider cloning them like this: 正如其他用户指出的那样,当您使用诸如startOf
和endOf
类的方法时, moment
的对象会发生endOf
,因此您应该考虑像这样克隆它们:
var startOfMonth = start.clone().startOf('month')
// ... and so on
If interested in using moment-range
plugin , use range.by
to get ranges. 如果对使用moment-range
插件感兴趣,请使用range.by
获取范围。
window['moment-range'].extendMoment(moment); var dateformat = "DD/MM/YYYY", start = moment("01/01/2018",dateformat), end = moment("01/12/2018",dateformat); var range = moment.range(start,end); var result = Array.from(range.by("month")).map(function(val){ return [val.startOf("month").format(dateformat),val.endOf("month").format(dateformat)]; }) console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-range/4.0.1/moment-range.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.