我要从此函数返回日期,为什么该函数还会更新StartDate控件的值, 例如:如果StartDate是15Dec2019,并且我想返回17Dec2019,并且此方法返回正确的值,但它还会使用该函数的返回日期更新StartDate控件的值。
此值不应在此函数内更新,在这里我得到的是控件值而不是更新。 this.createRecord.controls ['StartDate']。value
addDays(date: Date, days: number): Date {
date.setDate(date.getDate() + days);
return date;}
GetDueDate(): Date {
#region Recurring End Type -> No Of Occurences
debugger;
const dtStart: Date = this.createRecord.controls['StartDate'].value;
let returnDate: Date;
let dtEnd: Date = dtStart;
let FrequencyId: number = +this.createRecord.controls['FrequencyId'].value;
for (let i = 1; i < +this.createRecord.controls['Occurances'].value; i++)
{
//#region Next Date Calculation
if (FrequencyId == 1) {
dtEnd = this.addDays(dtStart, 1);//dtStart.(1);
}
else if (FrequencyId == 2) {
dtEnd = this.addDays(dtStart, 2);
}
else if (FrequencyId == 3) {
dtEnd = this.addDays(dtStart, 15);
}
else if (FrequencyId == 4) {
dtEnd = this.addMonths(dtStart,4);
}
else if (FrequencyId == 5) {
dtEnd = this.addMonths(dtStart, 3);
}
else if (FrequencyId == 6) {
dtEnd = this.addMonths(dtStart, 6);
}
else if (FrequencyId == 7) {
dtEnd = this.addYears(dtStart, 1);
}
//#endregion
returnDate = dtEnd;
}
//#endregion
return returnDate;
答案 0 :(得分:1)
日期是可变的。您应该创建新的日期。
const addDays = (date: Date, days: number): Date => {
const newDate = new Date(date.getTime())
newDate.setDate(newDate.getDate() + days);
return newDate;
}
const date = new Date();
const after2Days = addDays(date, 2);
console.log('date:',date);
console.log('after2Days:',after2Days);