When I click 'Previous' or 'Next' on the calendar, the start of the month shows the name of...

Discussão em 'Angular' iniciado por CodeRak, Janeiro 14, 2025.

  1. CodeRak

    CodeRak Guest

    I'm working on a calendar feature in an Angular application that displays the current week when navigating using "Previous" and "Next" buttons. However, I'm encountering an issue where the month name displayed does not align correctly with the actual dates shown in the calendar.

    For example:

    When navigating to the first week of January 2025 (e.g., January 1st to 4th), the calendar incorrectly shows "December 2024" as the month name, even though the dates displayed are from January.


    generateCurrentWeek(day: number, month: number, year: number): void {
    const selectedDate = new Date(year, month, day);

    // Ensure the selected date is consistent and not mutated
    const startOfWeek = new Date(selectedDate);
    startOfWeek.setDate(selectedDate.getDate() - selectedDate.getDay()); // Get the start of the week (Sunday)

    this.currentWeek = [];
    this.SelectedDateList = [];

    // Generate all 7 days of the week
    for (let i = 0; i < 7; i++) {
    const currentDate = new Date(startOfWeek);
    currentDate.setDate(startOfWeek.getDate() + i);

    // Format the date as YYYY-MM-DD
    const formattedDate = `${currentDate.getFullYear()}-${(currentDate.getMonth() + 1)
    .toString()
    .padStart(2, '0')}-${currentDate.getDate().toString().padStart(2, '0')}`;

    this.currentWeek.push({
    date: currentDate.getDate(),
    day: this.weekDays[currentDate.getDay()],
    });

    this.SelectedDateList.push({ date: formattedDate });
    }

    console.log('Current Week:', this.currentWeek);
    }

    previousWeek(): void {
    this.adjustWeek(-7);
    }

    nextWeek(): void {
    this.adjustWeek(7);
    }

    private adjustWeek(offsetDays: number): void {
    // Use the first day of the current week for calculations
    const firstDayOfCurrentWeek = new Date(
    this.selectedYear,
    this.selectedMonth,
    this.selectedDay
    );

    // Adjust by offsetDays
    firstDayOfCurrentWeek.setDate(firstDayOfCurrentWeek.getDate() + offsetDays);

    // Update selected date
    this.selectedYear = firstDayOfCurrentWeek.getFullYear();
    this.selectedMonth = firstDayOfCurrentWeek.getMonth();
    this.selectedDay = firstDayOfCurrentWeek.getDate();

    // Regenerate the week and fetch the employee list
    this.generateCurrentWeek(this.selectedDay, this.selectedMonth, this.selectedYear);
    this.GetEmployeeList(this.MainUserID);
    }

    Continue reading...

Compartilhe esta Página