0

i am returning date from this function , why this function also update the StartDate controls value, for ex: if StartDate is 15Dec2019 and i want to return 17Dec2019 , and this method returning correct value but it also update the StartDate control value with returning date from the function.

this value should not be updated inside this function , here i am getting control value not updaing.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;
1
  • Because you have a single Date object used for both, and muted using setDate(). Never, ever, ever call setDate(). Treat Date as an immutable class. Create a copy when you need another value. Commented Nov 30, 2019 at 14:57

1 Answer 1

1

Date is mutable. You should create new Date.

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.