Search code examples
javascriptdatedatepickerpikaday

Pikaday date range don't work


I used the range function from pikaday.

with onSelectI set the date range what actually works. Here is my example:

onSelect: function(date) {
    var first_ = (date.getDate() - date.getDay())+1;
    var last_ = first_ + 4;

    var firstday = new Date(date.setDate(first_));
    var lastday = new Date(date.setDate(last_));

    picker.setStartRange(firstday);
    picker.setEndRange(lastday);

    picker.draw();

    var f_startdate = firstday.getDate()+'.'+(firstday.getMonth()+1)+'.'+firstday.getFullYear();
    var f_enddate = lastday.getDate()+'.'+(lastday.getMonth()+1)+'.'+lastday.getFullYear();
    var kw = getWeekNumber(date.getFullYear()+'/'+(date.getMonth()+1)+'/'+date.getDate());

    document.getElementById('calendar').value = f_startdate+' - '+f_enddate;
    // document.getElementById('calendar').value = 'KW: '+(kw+1);
}

But when I select the 03.06.2016 the range is set to the "30.05.2016 - 03.05.2016" and the Input is wrong. Maybe anyone can help me.

Here is a working example: https://jsfiddle.net/24aL9f21/1/


Solution

  • Your issue is here:

    var first_ = (date.getDate() - date.getDay())+1;
    

    That gives you the date of the previous Monday, but also goes negative. 3 June is a Friday (day number 5), so first_ is set to:

    3 - 5 + 1 = -1
    

    Then:

    var last_ = first_ + 4;
    

    so last_ is set to 3. Now when you do:

    var firstday = new Date(date.setDate(first_));
    

    you are actually setting date to a date of -1, which is one before the start of the month so 30 May. setDate returns the time value, so firstday is a new Date instance set to 30 May also.

    Then:

    var lastday = new Date(date.setDate(last_));
    

    you are setting date to 3 May (remembering that in the line above you set it to 30 May). Again, the setDate method returns the time value, so a new Date object is created for that date. So you get dates for 30 May and 3 May (and if you check date, you'll set it's also 3 May).

    QED (which my Mathematics teacher told me was "Quite Easily Done"). ;-)

    So your code for the Monday is fine. If you want to get the date for the following Friday, just do:

    var lastday = date.setDate(date.getDate() + 4);
    

    Here lastday and date will reference the same Date object, but creating another copy doesn't seem useful.