简体   繁体   English

使用开始月份和结束月份的时刻获取一系列月份

[英]Get a range of months using moment with start month and end month

I am using a moment library and I would like to use it for getting an array of string months, with the starting date and the end date.我正在使用一个moment 库,我想用它来获取字符串月份数组,以及开始日期和结束日期。 So, for example when I have two dates:因此,例如当我有两个日期时:

const from = moment('2018-05-01', 'YYYY-MM-DD').format('MMMM');
  const to = moment('2018-07-01', 'YYYY-MM-DD').format('MMMM');

How can I then get the range of months as a string array, that would then look like this for the given dates:然后我怎样才能将月份范围作为字符串数组,对于给定的日期,它看起来像这样:

['May', 'June', 'July']

Is there a way we can achieve this with moment, and what would be the most elegant way to do this?有没有一种方法可以用 moment 来实现,最优雅的方法是什么?

Kindly, find the below format for moment.请暂时找到以下格式。

var fromDate = moment('2018-05-01','YYYY-MM-DD');
var toDate = moment('2018-07-01','YYYY-MM-DD');
var monthData = [];

while (toDate > fromDate || fromDate.format('M') === toDate.format('M')){

monthData.push(fromDate.format('MMMM'));
fromDate.add(1,'month');

}
console.log(monthData); // Output ["May", "June", "July"]

Thanks谢谢

You can use moment.months and slice it to get only needed months您可以使用moment.months并将其切片以获得仅需要的月份

 var months = moment.months(); console.log(JSON.stringify(months)) console.log(JSON.stringify(months.slice(4,7)))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

Just to show a solution without moment.js.只是为了展示一个没有 moment.js 的解决方案。

Month names are available in the browser default language using toLocaleString .使用toLocaleString以浏览器默认语言提供月份名称。 To get the names for months from the 3rd to 5th months inclusive, slice them from the array, eg要获取从第 3 个月到第 5 个月的月份名称,请将它们从数组中切片,例如

 /* Return array of month names for month number range in the * browser default language. * Eg 3,5 returns ['March','April','May] with default language English * Assumes Gregorian calendar, 12 months in year. If input is invalid, * returns an empty array * * @param {number|string} [startMonth=1] - calendar month number * @param {number|string} [endMonth=12] - calendar month number * @returns {string[]} Array of month names from startMonth to endMonth inclusive. */ var getMonthNames = (function () { var months = new Array(12).fill(0).map((v,i)=> new Date(2000,i).toLocaleString(undefined,{month:'long'}) ); return function(startMonth=1, endMonth=12) { return isNaN(+startMonth) || isNaN(+endMonth)? []: months.slice(--startMonth, endMonth); } }()); // Example [['03', '03'], // Single month ['06'], // Month to end of year [], // Month 1 to 12 ['01', '09'], // Month 1 to month 9 ['foo'] // Erroneous input ].forEach(args => console.log(`${args.toString()}: ${getMonthNames(...args).join(', ')}`) );

Creating the month name list is a little expensive, but it only runs once and it only needs 12 Dates so trivial.创建月份名单有点贵,但它只运行一次,而且只需要 12 个日期,非常简单。

It needs better error handling, eg check start <= end , 0 < start < 13 , 0 < end < 13 , start and end are integers, etc.它需要更好的错误处理,例如检查start <= end0 < start < 130 < end < 13startend是整数等。

If you are trying to get the month range in this format "2022-12-11T00:00:00+01:00 2022-12-17T23:59:59+01:00"如果您尝试以“2022-12-11T00:00:00+01:00 2022-12-17T23:59:59+01:00”格式获取月份范围

This would do the trick这样就可以了

const start = moment().subtract(1, 'week').startOf('week').format(); const start = moment().subtract(1, 'week').startOf('week').format();
const end = moment().subtract(1, 'week').endOf('week').format(); const end = moment().subtract(1, 'week').endOf('week').format();

I hope this was helpful我希望这可以帮到你

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

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