【问题标题】:Get a range of months using moment with start month and end month使用带有开始月份和结束月份的时刻获取一系列月份
【发布时间】:2018-10-17 09:37:05
【问题描述】:

我正在使用moment library,我想用它来获取包含开始日期和结束日期的字符串月份数组。因此,例如,当我有两个日期时:

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

然后我怎样才能将月份的范围作为字符串数组,然后对于给定的日期看起来像这样:

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

有没有一种方法可以让我们瞬间实现这一目标,最优雅的方法是什么?

【问题讨论】:

    标签: javascript date momentjs


    【解决方案1】:

    请暂时找到以下格式。

    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"]
    

    谢谢

    【讨论】:

      【解决方案2】:

      您可以使用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>

      【讨论】:

        【解决方案3】:

        只是为了展示一个没有 moment.js 的解决方案。

        使用toLocaleString 以浏览器默认语言提供月份名称。要获取从第 3 个月到第 5 个月(含)的月份的名称,请将它们从数组中切片,例如

        /* Return array of month names for month number range in the
         * browser default language.
         * E.g. 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(', ')}`)
        );

        创建月份名称列表有点贵,但它只运行一次,只需要 12 个日期,如此微不足道。

        它需要更好的错误处理,例如检查start <= end0 < start < 130 < end < 13startend是整数等

        【讨论】:

          猜你喜欢
          • 2021-01-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多