跳转至

2777. 日期范围生成器 🔒

题目描述

现给定起始日期 start 、结束日期 end 和正整数 step ,返回一个生成器对象,该生成器对象按照从 startend(包括 start 和 end )的范围生成日期。

step 的值表示连续生成的日期之间的天数间隔。

所有日期都以字符串格式 YYYY-MM-DD 表示。

 

示例 1:

输入:start = "2023-04-01", end = "2023-04-04", step = 1
输出:["2023-04-01","2023-04-02","2023-04-03","2023-04-04"]
解释:
const g = dateRangeGenerator(start, end, step);
g.next().value // '2023-04-01'
g.next().value // '2023-04-02'
g.next().value // '2023-04-03'
g.next().value // '2023-04-04'

示例 2:

输入:start = "2023-04-10", end = "2023-04-20", step = 3
输出:["2023-04-10","2023-04-13","2023-04-16","2023-04-19"]
解释:
const g = dateRangeGenerator(start, end, step);
g.next().value // '2023-04-10'
g.next().value // '2023-04-13'
g.next().value // '2023-04-16'
g.next().value // '2023-04-19'

示例 3:

输入:start = "2023-04-10", end = "2023-04-10", step = 1
输出:["2023-04-10"]
解释:
const g = dateRangeGenerator(start, end, step);
g.next().value // '2023-04-10'

 

提示:

  • new Date(start) <= new Date(end)
  • start 和 end 的日期格式是 YYYY-MM-DD
  • 0 <= 结束日期与开始日期之间的天数差 <= 1500
  • 1 <= step <= 1000

解法

方法一

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
function* dateRangeGenerator(start: string, end: string, step: number): Generator<string> {
    const startDate = new Date(start);
    const endDate = new Date(end);
    let currentDate = startDate;
    while (currentDate <= endDate) {
        yield currentDate.toISOString().slice(0, 10);
        currentDate.setDate(currentDate.getDate() + step);
    }
}

/**
 * const g = dateRangeGenerator('2023-04-01', '2023-04-04', 1);
 * g.next().value; // '2023-04-01'
 * g.next().value; // '2023-04-02'
 * g.next().value; // '2023-04-03'
 * g.next().value; // '2023-04-04'
 * g.next().done; // true
 */

评论