【问题标题】:How to Subtract Days From Date in TypeScript如何在 TypeScript 中从日期中减去天数
【发布时间】:2018-04-09 16:05:43
【问题描述】:

我想从 TypeScript 中的当前日期中减去天数。 例如,如果当前日期是 2017 年 10 月 1 日,我想减去 1 天得到 2017 年 9 月 30 日,或者如果我想减去 3 天,我得到 9 月 28 日等等。

这是我目前所拥有的,结果是我收到 1969 年 12 月 31 日。我认为这意味着 tempDate.getDate() 返回零,就像 1970 年 1 月 1 日的纪元一样。

这是我的代码,目标是返回前一个工作日。

    protected generateLastWorkingDay(): Date {

        var tempDate = new Date(Date.now());
        var day = tempDate.getDay();


        //** if Monday, return Friday
        if (day == 1) {
            tempDate = new Date(tempDate.getDate() - 3);
        } else if (1 < day && day <= 6) {
            tempDate = new Date(tempDate.getDate() - 1);
        }

        return tempDate;
    }

【问题讨论】:

    标签: datetime typescript


    【解决方案1】:

    getDate 返回月份中的日期 (1-31),因此从中创建一个新的 Date 将该数字视为“自纪元以来的毫秒数”。

    您可能想要的是使用 setDate 更改日期,因为它会自动处理数月/数年的倒退。

    protected generateLastWorkingDay(): Date {
      const lastWorkingDay = new Date();
    
      while(!this.isWorkingDay(lastWorkingDay)) {
        lastWorkingDay.setDate(lastWorkingDay.getDate()-1);
      }
    
      return lastWorkingDay;
    }
    
    private isWorkingDay(date: Date) {
      const day = date.getDay();
    
      const isWeekday = (day > 0 && day < 6);
    
      return isWeekday; // && !isPublicHoliday?
    }
    

    【讨论】:

    • new Date(Date.now()) 是多余的。你可以简单地做new Date()
    【解决方案2】:

    我就是这样做的

    let yesterday=new Date(new Date().getTime() - (1 * 24 * 60 * 60 * 1000));
    let last3days=new Date(new Date().getTime() - (3 * 24 * 60 * 60 * 1000));
    

    我们需要从当前日期减去(no_of_days) * 24 * 60 * 60 * 1000

    【讨论】:

      【解决方案3】:

      你可以

      const current = new Date()
      

      然后

      const numberOfDaysToSubstract= 3;
      
      const prior = new Date().setDate(current.getDate) - numberOfDaysToSubstract);
      

      你可以在这里看到一个例子

      https://codepen.io/Jeysoon/pen/poNZRwd?editors=1112

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-01
        • 2012-10-07
        • 1970-01-01
        • 1970-01-01
        • 2010-11-20
        • 2013-02-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多