javascriptjquerytimezonedatetimepicker

Jquery datetimepicker last day of month not working


I have a filter page with 2 datetimepicker as Start date (first day of month) and End date (last day of month). This is what I'm trying to do:

$(document).ready(function () {

    var date = new Date(2025, 3, 22);
    var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
    var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

    console.log("date");
    console.log(date);
    console.log("firstDay");
    console.log(firstDay);
    console.log("lastDay");
    console.log(lastDay);
    
    $('#StartDate').datetimepicker({
        defaultDate: firstDay,
        locale: 'en-ie',
        format: 'DD/MM/YYYY',
        showClose: true,
        showClear: true,
        ignoreReadonly: true,
        minDate: '1900-01-01',
        allowInputToggle: true
    });

    $('#EndDate').datetimepicker({
        defaultDate: lastDay,
        locale: 'en-ie',
        format: 'DD/MM/YYYY',
        showClose: true,
        showClear: true,
        ignoreReadonly: true,
        minDate: '1900-01-01',
        allowInputToggle: true
    });
}

The error:

For example, if the date is 22/04/2025, the firstDay will be 01/04/2025 and the lastDay will be 30/04/2025. But my datimepickers showing fistDay as 31/03/2025 and lastDay as 29/04/2025. 1 day before the correct dates. In console log my variables is correct but when I try to query my components value, I see the wrong days.

Console log

Console log variables

I've looked in several places and I can't find the reason for this error.


Solution

  • I did many kind of tests and the problem is the summer time (1 hour increased). I tested with past dates without summer time, like december, and the firstDate and lastDate showing correctly (01/12/2024 and 31/12/2024).

    Just remove the increased hours to work fine!

    firstDay.setMinutes(firstDay.getMinutes() - firstDay.getTimezoneOffset());
    lastDay.setMinutes(lastDay.getMinutes() - lastDay.getTimezoneOffset());
    

    if there is no summer time, no hours are taken away.

    This thread helped me build the solution:

    How to avoid time zone issues with JQuery datepicker