【问题标题】:Calculation of previous day through yesterday.setDate(currentDay.getDate() - 1) fails通过昨天.setDate(currentDay.getDate() - 1) 计算前一天失败
【发布时间】:2020-12-03 10:06:26
【问题描述】:

我正在尝试计算当前和前 6 天的日期。这should work 只需从上一个日期减去 1,所以我实现了我当前的解决方案,如下所示:

        let currentDay = new Date();
        let nextDay = new Date();
        for (let i = 0; i < 7; i++) {
            nextDay.setDate(currentDay.getDate() - i);
            console.log("i=" + i + "->" + nextDay);
        }

但是,这是输出:

i = 0 -> Thu Dec 03 2020 10: 20: 51 GMT + 0100(Central European Standard Time)  //today
i = 1 -> Wed Dec 02 2020 10: 20: 51 GMT + 0100(Central European Standard Time)  //yesterday
i = 2 -> Tue Dec 01 2020 10: 20: 51 GMT + 0100(Central European Standard Time)  //day before yesterday
i = 3 -> Mon Nov 30 2020 10: 20: 51 GMT + 0100(Central European Standard Time)  //3 days ago
i = 4 -> Fri Oct 30 2020 10: 20: 51 GMT + 0100(Central European Standard Time)  //skips an entire month
i = 5 -> Mon Sep 28 2020 10: 20: 51 GMT + 0200(Central European Summer Time)    //skips another month, 2 days and switches to summertime
i = 6 -> Fri Aug 28 2020 10: 20: 51 GMT + 0200(Central European Summer Time)    //skips another month

在上个月末运行时,它按预期工作(当前月份没有转义)。它在进入 11 月时失败了。我似乎找不到原因。

【问题讨论】:

    标签: typescript date


    【解决方案1】:

    您永远不会从第一天开始重新创建nextDate。看看这个:

    function addDays(a_oDate: Date, days: number): Date {
      a_oDate.setDate(a_oDate.getDate() + days);
      return a_oDate;
      }
    
    function printLast7Days(a_oDate: Date): void {
      for (let i = 0; i < 7; i++) {
        let nextDay = new Date(a_oDate); // recreate date from the initial date
        addDays(nextDay, -i); // effectively subtracts i days
        console.log("i=" + i + "->" + nextDay.toDateString());
        }
    }
    
    printLast7Days(new Date());
    

    Playground

    【讨论】:

    • 谢谢,添加nextDay = new Date(currentDay); 实际上修复了它。我仍然无法理解我的错误在哪里。我的解决方案应该:计算常数currentDay;初始化nextDay一次;将nextDay 设置为currentDay - n * amount。不重新初始化的结果不应该是一样的吗?
    • @Beltway 如果setDate() 收到负数,它将切换月份,这很好,但是 - 在您的情况下,nextDate 已经在过去的一个月内经过 4-5 次迭代,它将继续切换月份,因为 nextDate 永远不会重置为当前日期
    猜你喜欢
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2011-07-27
    • 1970-01-01
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多