题目描述:

题目:给定一个开始日期’2022-08’,一个结束日期’2023-02’

要求:实现一个函数getMonthArray,返回开始日期到结束日期中间的所有月份[‘2022-09’, ‘2022-10’, ‘2022-11’, …, ‘2023-01’]

知识点

  • 字符串的拼接与截取
  • 数字类型与字符串类型的相互转换
  • 月份与年的计算

实现思路

  1. 根据入参截取出开始年份、月份。
  2. 计算两个日期实际相差几个月。
  3. 循环拼接日期,放入到数组中,需要注意月份大于12时,需重置为1,同时年份+1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function getMonthArray(startDate, endDate) {
let startYear = parseInt(startDate.split('-')[0])
let startMonth = parseInt(startDate.split('-')[1])
let yearDiff = parseInt(endDate.split('-')[0]) - startYear
let monthDiff = parseInt(endDate.split('-')[1]) - startMonth
let totalMonth = yearDiff * 12 + monthDiff
let result = []

for (let i = 1; i < totalMonth; i++) { // 这里i = 1 是因为只计算到截止日期的前一个月
startMonth++
if (startMonth > 12) {
startMonth = 1
startYear++
}
let temp = String(startMonth).length < 2 ? `0${startMonth}` : startMonth
result.push(`${startYear}-${temp}`)

}
return result
}

const arr = getMonthArray('2022-08', '2023-02')
console.log(arr); // [ "2022-09", "2022-10", "2022-11", "2022-12", "2023-01" ]

变种题型:需要返回开始和结束月份

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function getMonthArray(startDate, endDate) {
let startYear = parseInt(startDate.split('-')[0])
let startMonth = parseInt(startDate.split('-')[1])
let yearDiff = parseInt(endDate.split('-')[0]) - startYear
let monthDiff = parseInt(endDate.split('-')[1]) - startMonth
let totalMonth = yearDiff * 12 + monthDiff
let result = []

for (let i = 0; i <= totalMonth; i++) {
let temp = String(startMonth).length < 2 ? `0${startMonth}` : startMonth
result.push(`${startYear}-${temp}`)
startMonth++
if (startMonth > 12) {
startMonth = 1
startYear++
}

}
return result
}

const arr = getMonthArray('2022-08', '2023-02')
console.log(arr); // [ "2022-08", "2022-09", "2022-10", "2022-11", "2022-12", "2023-01", "2023-02" ]

小结

这道面试题主要考察了字符串的截取,以及对年和月份的转化。这类题其实还可以有很多种变种问法,比如根据起止日期计算相差多少年多少月,实现思路大体相同,只需要根据实际情况修改代码返回相应的值即可。