简体   繁体   English

MomentJS - 获取日期范围给出一个月中的特定日期

[英]MomentJS - Get date range give a specific day of the month

Given day of the month of 5 how would you best get the date range between the 5th of last/this month and the next 5th of the month?给定一个月的5日,您如何最好地获得上/本月 5 日和下个月 5 日之间的日期范围?

// given today is May 24 2021
// should return May 5 - June 5
function getDateRange(selectedDay) {
  const today = moment()
  let previous, next
  if (today.date() >= selectedDay) {
    previous = today.clone().set('date', selectedDay)
    next = today.clone().add(1, 'months').set('date', selectedDay)
  }
  else {
    previous = today.clone().subtract(1, 'months').set('date', selectedDay)
    next = today.clone().set('date', selectedDay)
  }

  return [ previous, next ]
}

This works most of the time except for when the selected day doesn't exist for the month (ie. 31st).这在大多数情况下都有效,除非当月不存在选定的日期(即 31 日)。

For example, if today's date was Feb 15, 2021 and the selectedDay is 31 , the function should return Jan 31 - Feb 28 .例如,如果今天的日期是Feb 15, 2021并且selectedDay31 ,则 function 应该返回Jan 31 - Feb 28

Does anyone have an elegant solution to this?有没有人对此有一个优雅的解决方案?

I edit a bit your code and insert a function to determiante the max date of the month.我对您的代码进行了一些编辑并插入了 function 来确定该月的最大日期。

 // To force a date I inserted a initDate like parameters, remove it if it's unnecessary function getDateRange(selectedDay, initDate) { const today = moment(initDate); let previous; let next; if (today.date() >= selectedDay) { previous = moment(today).startOf('month'); next = moment(today).add(1, 'month').startOf('month'); } else { previous = moment(today).subtract(1, 'months'); next = moment(today); } previous = limiter(previous, selectedDay); // this function get the max date of the month next = limiter(next, selectedDay); return [previous, next]; } function limiter(dateToLimit, selectedDay) { if (moment(dateToLimit).endOf('month').isBefore(moment(dateToLimit).date(selectedDay))) dateToLimit = moment(dateToLimit).endOf('month'); else dateToLimit = moment(dateToLimit).date(selectedDay); return dateToLimit; } console.log(getDateRange(31, '2021-02-15')); console.log(getDateRange(31, '2021-03-15')); console.log(getDateRange(13, '2021-02-15')); console.log(getDateRange(13, '2021-09-15')); console.log(getDateRange(26, '2021-09-15')); console.log(getDateRange(26, '2021-09-27'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.25.1/moment.min.js"></script>

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

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