我有以下功能:
public static addDaysNextPrev(operation: number, date: Date = new Date(), days: number = 7): IDateCalendarNextPrev {
const currentDate = new Date(date);
const prevDate = new Date(date);
currentDate.setDate(currentDate.getDate() + (days * operation));
prevDate.setDate(currentDate.getDate() - (days * operation));
console.log(prevDate);
}
我尝试添加/减去当前日期的某些天。想法是将7天添加到当前日期并返回上一个和下一个。
参数operation
是数字1
或正数或负数,用于确定下一个日期或上一个日期的方向。
我总是排错日期:
console.log(prevDate);
这是我的第二个解决方案,更明显:
public static addDaysNextPrev(operation: boolean, date: Date = new Date(), days: number = 7): IDateCalendarNextPrev {
let currentDate = new Date(date);
let prevDate = new Date(date);
if (operation) {
prevDate = date;
currentDate.setDate(currentDate.getDate() + days);
} else {
currentDate.setDate(date.getDate() - days);
prevDate.setDate(currentDate.getDate() - days);
}
}
答案 0 :(得分:2)
您在第currentDate
行添加了7天的时间:
currentDate.setDate(currentDate.getDate() + (days * operation));
并在该行减去currentDate
的7天:
prevDate.setDate(currentDate.getDate() - (days * operation));
因此,您的prevDate
将与currentDate
初始值具有相同的值。
此处更正:
let operation = 1;
let date: Date = new Date();
let days: number = 7
const currentDate = new Date(date);
const prevDate = new Date(date);
prevDate.setDate(currentDate.getDate() - (days * operation));
console.log(prevDate);