The*_*l26 5 datetime typescript
我想从 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;
}
Run Code Online (Sandbox Code Playgroud)
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?
}
Run Code Online (Sandbox Code Playgroud)
我就是这样做的
let yesterday=new Date(new Date().getTime() - (1 * 24 * 60 * 60 * 1000));
let last3days=new Date(new Date().getTime() - (3 * 24 * 60 * 60 * 1000));
Run Code Online (Sandbox Code Playgroud)
我们需要(no_of_days) * 24 * 60 * 60 * 1000从当前日期减去。
| 归档时间: |
|
| 查看次数: |
14442 次 |
| 最近记录: |