返回介绍

solution / 2700-2799 / 2777.Date Range Generator / README_EN

发布于 2024-06-17 01:03:00 字数 3110 浏览 0 评论 0 收藏 0

2777. Date Range Generator

中文文档

Description

Given a start date start, an end date end, and a positive integer step, return a generator object that yields dates in the range from start to end inclusive. All dates are in the string format YYYY-MM-DD. The value of step indicates the number of days between consecutive yielded values.

 

Example 1:

Input: start = "2023-04-01", end = "2023-04-04", step = 1
Output: ["2023-04-01","2023-04-02","2023-04-03","2023-04-04"]
Explanation: 
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'

Example 2:

Input: start = "2023-04-10", end = "2023-04-20", step = 3
Output: ["2023-04-10","2023-04-13","2023-04-16","2023-04-19"]
Explanation: 
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'

Example 3:

Input: start = "2023-04-10", end = "2023-04-10", step = 1
Output: ["2023-04-10"]
Explanation: 
const g = dateRangeGenerator(start, end, step);
g.next().value // '2023-04-10'

 

Constraints:

  • new Date(start) <= new Date(end)
  • 0 <= The difference in days between the start date and the end date <= 1000
  • 1 <= step <= 100

Solutions

Solution 1

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
 */

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文