gpt4 book ai didi

javascript - 以字符串数组形式返回两个日期之间的月数

转载 作者:行者123 更新时间:2023-12-02 21:18:52 31 4
gpt4 key购买 nike

//So I have and array of months
const months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'];

// If the input is startDate: 1-1-2019 & endDate: 3-15-21
// It should return an array like so:

const monthsBetweenDates = [January,February,March,April,May,June,July,August, September, October, November,December, January,February,March,April,May,June,July,August, September, October, November, December, January, Feb, March];

// The returned/new array should have all months between the start and end date above in Order, duplicated needed in order as well.

非常感谢您的帮助和时间。如果您还有任何疑问,请告诉我。

最佳答案

简单的算术解决方案

<小时/>

考虑到目标,我想说用基本数学来解决任务比处理 Date 类型更有意义。

您所需要的是:

  • destructure开始和结束日期的日期字符串 (m-d-yyyy),分为开始/结束月份和年份 (mStartyStartmEnd, yEnd):
const [mStart, , yStart] = start.split('-'),
[mEnd, , yEnd] = end.split('-')
  • 计算期间的总长度(以月为单位,包括开始和结束)
12*(yEnd-yStart)+(mEnd-mStart)+1}
  • 返回array相应的长度,其中每一项都将从源 month 数组中取出,旋转移动一个位置:
months[(mStart-1+i)%months.length]
<小时/>

您可以在下面找到完整的演示:

const startDate = '1-1-2019',
endDate = '3-15-2021',

monthsBetweenDates = (start,end) => {
const months = ['January','February','March','April','May','June','July','August','September','October','November','December'],
[mStart, , yStart] = start.split('-'),
[mEnd, , yEnd] = end.split('-')
return Array.from(
{length: 12*(yEnd-yStart)+(mEnd-mStart)+1},
(_,i) => months[(mStart-1+i)%months.length]
)
}

console.log(monthsBetweenDates(startDate,endDate))
.as-console-wrapper{min-height:100%;}

关于javascript - 以字符串数组形式返回两个日期之间的月数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60903987/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com