【问题标题】:How to manage date using momentjs for a monthly payments?如何使用momentjs管理日期以进行每月付款?
【发布时间】:2021-08-24 08:12:13
【问题描述】:

大家好,我已经每周和每两周实施一次,但我需要使用momentjs每月实施一次,以满足以下特定要求

可能的付款频率为: ● 每周 ● 每月 - 每月同一天(例如 3 月 5 日、4 月 5 日、5 月 5 日) 对于每月频率,如果某个订单项的开始日期在某些月份不存在,我们 需要在该月最近的一天进行下一次付款。例如,租约 从 8 月 31 日开始的每月付款频率不能有下一个 9 月 31 日付款,因为 9 月 31 日不存在。因此我们将 9月30日有下一次付款,之后的付款将是31日 10 月,恢复到该月的原始日期。

【问题讨论】:

    标签: node.js express momentjs


    【解决方案1】:

    您可以使用moment().endOf(String) 来检查当月的最后一天,请参阅文档https://momentjs.com/docs/#/manipulating/end-of/

    也检查这个答案Moment JS start and end of given month

    【讨论】:

      【解决方案2】:

      您也可以使用普通 JavaScript 获取每个月的付款日期,方法是创建一个 Date 对象,该对象的 monthIndex 为所需的 monthIndex + 1,如果该月的天数小于 0,则为 0付款日。

      我们可以使用Array.from()Array.map() 创建一个租赁付款日期数组:

         
      // Get the number of days in a given month...
      function getDaysInMonth (year, month) {
          return new Date(year, month, 0).getDate();
      }
      
      // Create an array of the dates in question
      function getPaymentDates(startYear, startMonth, dayOfMonth, termMonths) {
          return Array.from({ length: termMonths }, (v, monthOffset) => {
              const daysInMonth = getDaysInMonth(startYear, startMonth + monthOffset);
              if (dayOfMonth <= daysInMonth) {
                  return new Date(startYear, startMonth + monthOffset - 1, dayOfMonth)
              } else {
                  // Return the last day of the month 
                  return new Date(startYear, startMonth + monthOffset, 0)
              }
          });
      }
      
      // Log the dates in a convenient format
      const options = { year: 'numeric', month: 'numeric', day: 'numeric' }
      
      // Test with some different payment days... 
      const days = [1,15,30,31];
      for(let dom of days) {
         console.log(`Payment dates (DOM = ${dom}):`, getPaymentDates(2021, 8, dom, 12).map(d => d.toLocaleDateString([], options)))
      }

      【讨论】:

        猜你喜欢
        • 2011-04-24
        • 2011-01-28
        • 1970-01-01
        • 2016-04-28
        • 2015-04-13
        • 2021-01-10
        • 2017-05-12
        • 1970-01-01
        • 2017-02-09
        相关资源
        最近更新 更多