Search code examples
javascriptjquerydaterangeslider

How to get the date one month before from current date, when current date is January?


I used a plugin called jQRnageSlider and tried to get the date and time label showed in the slider, but when I scroll back the slider to last year, the month 12 turns out to be 11 eventually.

enter image description here

Normal case if I don't scroll back to last year.

enter image description here

It jumped to Nov 2016 immediately

That should be the issue of date formatting issue. Can anyone help?

$(".date-range-slider").dateRangeSlider({    
  ...

  formatter: function(val){
    var days = ('0' + val.getDate()).slice(-2),
    month = ('0' + val.getMonth() + 1).slice(-2),
    year = val.getFullYear(),
    hour = ('0' + val.getHours()).slice(-2),
    min = ('0' + val.getMinutes()).slice(-2);
    return days + "-" + month + "-" + year + " " + hour + ":" + min;
  }
});

Solution

  • The problem is that line:

    month = ('0' + val.getMonth() + 1).slice(-2)

    You want to sum it mathematically not as string, so you should do:

    month = ('0' + (val.getMonth() + 1)).slice(-2)

    Check the snippet to see what your code is actually returning:

    var val = new Date();
    document.write('0' + val.getMonth() + 1)

    And what returns corrected version:

    var val = new Date();
    document.write('0' + (val.getMonth() + 1))