if by end of the period person is greater than 18 i want childEndDate to be the date of person's date when he/she will become 18 years old.
in my else if statement i am using date-fns library to add 18 years to dates i have in my this.childBirthDate array. but returned output is wrong: ["1988-01-01T00:00:02.012Z", "1988-01-01T00:00:02.010Z", "2031-11-08T13:24:43.704Z"]
output i want returned is: ['2030-02-16T20:00:00.000Z', '2028-05-19T20:00:00.000Z', 2031-11-08T13:24:43.704Z]
here is my stackblitz
this.childBirthDate = [
'2012-02-16T20:00:00.000Z',
'2010-05-19T20:00:00.000Z',
'2016-05-19T20:00:00.000Z',
];
//enddate
const endYear = date.getFullYear() + 10;
date.setFullYear(endYear);
this.endDate = date.toISOString();
this.childBirthDate.forEach((element) => {
const birthYear = element.substring(0, 4);
this.childbirthYear.push(+birthYear);
});
const periodEndYear = +this.endDate.substring(0, 4);
// calculate child endDate
this.childbirthYear.forEach(element => {
if (periodEndYear - element < 18) {
this.childEndDate = this.endDate;
} else if (periodEndYear - element >= 18) {
this.childEndDate = addYears(new Date(element), 18).toISOString();
}
this.final.push(this.childEndDate);
});
console.log(this.final)
this.personalInfo = {
personalInfoId: 0,
underageChildInfo: this.data.underageChildInfo?.map((i, index) => ({
firstName: i.name,
endDate: this.final[index],
})),
};
I think your logic to get the end date is reproducing what you want. However, I think your code may be hard to follow due to all the extra variables.
If you remove the foreach loops in favor of some map operators, your code will log the dates you are looking to get.
e.g.
// in ngOnInit
this.finalDates = this.childBirthDate.map(date => {
return this.calculateDate(date);
});
// outputs ["2030-02-16T20:00:00.000Z", "2028-05-19T20:00:00.000Z", "2031-11-08T14:28:01.761Z"]
console.log(this.finalDates);
// custom method on the class
calculateDate(date: string): string {
const periodEndYear = +this.endDate.substring(0, 4);
const year = parseInt(date.substring(0, 4), 10); // get a number from string
if (periodEndYear - year < 18) {
return this.endDate;
} else if (periodEndYear - year >= 18) {
return addYears(new Date(date), 18).toISOString();
}
return date;
}
here is a fork of your blitz