javascripttypescripttypescript2.0typescript2.2

Why Date() returns wrong date?


I have the following function:

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);

}

I try to add/minus some days from current date. Idea is to add 7 days to current date and return prev date and next.

Parameter operation is number 1 or positive or negative that determine direction to next date or to prev date.

I always get wrong date in line:

console.log(prevDate);

This is my second solution, more obviously:

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);
    }
}

Solution

  • You're adding 7 days to currentDate at line:

    currentDate.setDate(currentDate.getDate() + (days * operation));
    

    and subtracting 7 days of currentDate at the line:

    prevDate.setDate(currentDate.getDate() - (days * operation));
    

    So your prevDate will have the same value as currentDate initial value.

    Correction here:

    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);