使用Moment.js

时间:2017-04-11 20:31:01

标签: javascript node.js jasmine momentjs jest

我需要帮助编写一个函数,该函数基于具有不同间隔nextDueDateinitialDueDatequarterly的{​​{1}}来获取yearly

该方法的伪代码看起来像 -

如果将来monthly,请返回initialDueDate 否则,如果间隔为initialDueDate,请继续向quarterly添加3个月,直到找到将来的日期为止。

这是我试图通过的测试:

initialDueDate

2 个答案:

答案 0 :(得分:1)

我想在Yohanes Gultom'答案中添加一些内容。处理未来案例并使函数递归。希望它有所帮助。

// test.js
const INTERVAL = {
  monthly: moment.duration(1, 'months'),
  quarterly: moment.duration(3, 'months'),
  yearly: moment.duration(1, 'years')
}

function calculateNextDueDate(initialDueDate, intervalCode) {
  if(moment().diff(initialDueDate) < 0)
    return initialDueDate;
  else 
  return calculateNextDueDate(initialDueDate.add(INTERVAL[intervalCode]), intervalCode);
}

// usage
console.log(calculateNextDueDate(moment('2017-01-01', 'YYYY-MM-DD'), 'monthly').format('YYYY-MM-DD') )
console.log(calculateNextDueDate(moment('2017-01-01', 'YYYY-MM-DD'), 'quarterly').format('YYYY-MM-DD'))
console.log(calculateNextDueDate(moment('2017-01-01', 'YYYY-MM-DD'), 'yearly').format('YYYY-MM-DD') )
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

答案 1 :(得分:0)

我喜欢@ anshulk的递归算法,但它没有考虑到几个月的天数有不同的长度。从我的评论:

  

例如,尝试下面的代码,从1月31日开始,添加一个月,然后是另一个,最后是3月28日,当你可能想要3月31日时:

moment.utc('2017-01-31 12:00:00')
  .add(moment.duration(1, 'month'))
  .add(moment.duration(1, 'month'))

基本上相同的算法应该直接用.month(X)设置月份。有关momentjs'month()的有趣之处在于它可以超过11,所以12代表明年1月(与现在相比12个月不一样),29代表未来2个日历年,第5个月(6月)在片刻)。

所以这应该有效:

function calculateNextDueDate(initialDueDate, momentMonth, intervalInMonths) {
  const modifiedDate = moment.utc(initialDueDate).month(momentMonth)
  if (moment.utc().diff(modifiedDate) < 0) {
    return modifiedDate
  }
  return calculateNextDueDate(initialDueDate, momentMonth + intervalInMonths, intervalInMonths)
}

这是一个测试:

// Usage:
var startDate = moment.utc('2017-01-31')
console.log(calculateNextDueDate(startDate, startDate.months(), 1))
console.log(calculateNextDueDate(startDate, startDate.months(), 3))
console.log(calculateNextDueDate(startDate, startDate.months(), 12))

请注意moment's objects are mutable!该算法不会改变传入的原始值,这对您来说可能重要也可能不重要。

另外,我到处都使用moment.utc()