【问题标题】:how to pick up date time range for every Monday in specific range of date如何在特定日期范围内获取每个星期一的日期时间范围
【发布时间】:2020-10-09 12:11:31
【问题描述】:

我正在尝试获取特定时间段内每个星期一的日期时间范围,我可以从本月到年底执行此操作,但我可以动态设置时间段。

This is my code 

enum DAYS {
    MON = 1,
    TUE,
    WED,
    THU,
    FRI,
    SAT,
    SUN
}

function getDays(day) {
    const d = new Date(new Date().setHours(0, 0, 0, 0)),
        month = d.getMonth(),
        days = [];
    d.setDate(day);
    while (d.getDay() !== day) {
        console.log('d')
        d.setDate(d.getDate() + 1);
    }

    while (d.getMonth()) {
        const date = new Date(d.getTime())
        const start = date.getTime()
        const end = start + 24 * 60 * 60
        const range = {
            date,
            start,
            end
        }
        days.push(range);
        d.setDate(d.getDate() + 7);
    }

    return days;
}

const Mondays = getDays(DAYS.MON)
const Tuesdays = getDays(DAYS.TUE)
console.log(Mondays)
console.log(Tuesdays)

例如,如果我想从 2019 年 6 月 14 日到 2020 年 6 月 13 日整个星期一,我如何将期间设置为开始日期和结束日期? 你能请人给我建议吗?

【问题讨论】:

  • enum 是一个未来的reserved word,哪个实现正在使用它?
  • while (d.getMonth()) 将在 getMonth 返回 0 时在 1 月停止。您需要为范围结束创建一个日期,例如称为 endDate i>,然后做while (d < endDate)。
  • 您好 RobG,感谢您的提示。正如你所说,我将 d.getMonth() 替换为 endDate 并成功实现了这一点。谢谢你。我附上了未来提问者的代码!

标签: javascript datetime timestamp


【解决方案1】:
    enum DAYS {
    MON = 1,
    TUE,
    WED,
    THU,
    FRI,
    SAT,
    SUN
}

function getDays(day, startDate, endDate) {
    const d = new Date(startDate)
    const days = [];
    d.setDate(day);
    while (d.getDay() !== day) {
        d.setDate(d.getDate() + 1);
    }
    while (d < endDate) {
        if (d >= startDate) {
            const date = new Date(d.getTime())
            const start = date.getTime()
            const end = start + 24 * 60 * 60
            const range = {
                date,
                start,
                end
            }
            days.push(range);
        }
        d.setDate(d.getDate() + 7);
    }

    return days;
}

const startDate = new Date('Thu Jan 20 2020 00:00:00 GMT+0900 (Japan Standard Time)')
const endDate = new Date('Thu Jun 19 2022 00:00:00 GMT+0900 (Japan Standard Time)')
const day = DAYS.MON
const Mondays = getDays(day, startDate, endDate)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-14
    • 2014-01-07
    • 1970-01-01
    • 2014-11-01
    • 1970-01-01
    • 2013-09-12
    • 2017-02-23
    • 1970-01-01
    相关资源
    最近更新 更多