Nouslider Time slider returns incorrect timestamps

198 Views Asked by At

I am making a time slider using nouilsider. I have year-month values for the slider which looks like [1979-03, 1979-06,1979-09,1979-12,1980-03] which are at an interval of three months. Since my start value is 1979-03 it should return me the timestamp for 1979-03 but when I check the month of the time stamp it returns me 1 rather than 3. Secondly, my slider only slides a bit.This is my code

    function timestamp(str) {
      var x = (new Date(str).getTime());
      return x;
    }
    noUiSlider.create(stepSlider, {
            start: timestamp('1979-01'),
            range: {
                'min': timestamp('1979-01'),
                'max': timestamp('1979-06')
            },
            step: 3*30 * 24 * 60 * 60 * 1000


        });
stepSlider.noUiSlider.on('update', function (values, handle) {
   var x = parseInt(values[handle]);
   var date = new Date(x);
   var month = date.getMonth()
   console.log(month)
1

There are 1 best solutions below

0
On

Your step value of 3*30 * 24 * 60 * 60 * 1000 does not match full months. Not all months have 30 days, and not all days have 24 * 60 * 60 seconds.

Since you are using a fixed number of steps, you'd be better of using integers and mapping the output to months:

var slider = document.getElementById('slider');

noUiSlider.create(slider, {
    start: 0,
    range: {
        'min': 0,
        'max': 5
    },
    format: {
        to: function(value) {
            return ['1979-01', '1979-02', '1979-03', '1979-04', '1979-05', '1979-06'][Math.round(value)];
        },
        from: Number
    },
    step: 1
});

slider.noUiSlider.on('update', function( values, handle ) {
    console.log(values[handle]);
});