Search code examples
javascripthtmltwitter-bootstrap-3momentjsbootstrap-slider

Insert all remaining dates until a specific date into a slider


I am using a bootstrap slider for an interest calculator, where I can slide an amount from 0 - 15.000 DKK and another slider that contains remaining days until a specific dates.

Those two slider will calculate the interest when money is inserted at specific dates.

My problem now is that I want the slider tooltip to show sequential dates, i.e at page load the slider will start on todays date (3 March 2016), then when I slide it 4 steps the tooltip should show 7 March 2016, and if I slide it 30 steps it should show 2 April.

The slider is initialised with this:

$(".date").slider({
    tooltip: 'always',
    min: 1,
    max: daysRemaining,
    step: 1,
    value: daysRemaining,
    formatter: function (daysRemaining) {
       DateOutputFunction here
     }
 });

daysRemaining are found using moment.js

var today = moment();
var lastDate = moment("20161212");
var daysRemaining = lastDate.diff(today, "days");

Solution

  • You can use moment add and moment format to get what you need, for example:

    var today = moment();
    var lastDate = moment("20161212");
    var daysRemaining = lastDate.diff(today, "days");
    
    $(".date").slider({
        tooltip: 'always',
        min: 1,
        max: daysRemaining,
        step: 1,
        value: daysRemaining,
        formatter: function (value) {
            var today = moment();
            var day = today.add(value, "days");
            return day.format("D MMMM YYYY");
        }
     });
    .slider{
      margin: 50px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/6.1.1/bootstrap-slider.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>
    
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/6.1.1/css/bootstrap-slider.min.css">
    
    <input type="text" class="date">