Search code examples
jquerymomentjstempus-dominus-datetimepicker

Selecting last day of week in datetimepicker


I'm using moment.js to try to select the last day of the week that is selected in the datetimepicker but it returns a continuous loop for every last day of every week. I'm not sure what I am doing wrong please could someone help me.

This is the JS that I have tried.

JS

$(datePick).on('change.datetimepicker', () => {
    var datetimePicker = $("#datetimepicker1").val();
    lastDate = moment(datetimePicker, "YYYY-MM-DD").day(7).format("YYYY-MM-DD");
    $(datePick).val(lastDate);
});

Thank you!


Solution

  • In your example, you don't select the last day of the week, but the Sunday of the next week by using moment(...).day(7). After that you set the value, which will trigger the on change function again, setting the value to the Sunday a week later. And so on... (continuous loop)

    So you need to change moment(...).day(7) to moment(...).day(6), which will select the Saturday of the current week. In the second try, it will not change the value again and the loop stops.

    If you want to select the next Sunday as the end of the week instead of Saturday, I suggest doing something like

    $(datePick).on('change.datetimepicker', () => {
        var datetimePicker = $("#datetimepicker1").val();
        if (moment(datetimePicker.day() !== 0) {
            lastDate = moment(datetimePicker, "YYYY-MM-DD").day(7).format("YYYY-MM-DD");
            $(datePick).val(lastDate);
        }
    });