user9632680
user9632680

Reputation:

Pick a date range in single Bootstrap Datepicker

I am using Bootstrap DatePicker v1.8.0

Need to select range in a single bootstrap and I need the input value to be arranged in ascending order (example below).

enter code here

Upvotes: 1

Views: 6011

Answers (1)

Vignesh Raja
Vignesh Raja

Reputation: 8751

On changing the date, the date array is appended with the new date. Get the dates and parse it in changeDate event listener and set it again.

$('#date').datepicker({
    format: "M yyyy",
    startView: 1,
    minViewMode: 1,
    maxViewMode: 2,
    multidate: true,
    multidateSeparator: "-",
    autoClose:true,
}).on("changeDate",function(event){
      var dates = event.dates, elem=$('#date');
      if(elem.data("selecteddates")==dates.join(",")) return; //To prevernt recursive call, that lead to lead the maximum stack in the browser.
      if(dates.length>2) dates=dates.splice(dates.length-1);
      dates.sort(function(a,b){return new Date(a).getTime()-new Date(b).getTime()});
      elem.data("selecteddates",dates.join(",")).datepicker('setDates',dates);
});

function getDates()
{
    console.log($("#date").datepicker("getDates"));
    console.log($("#date").datepicker("getUTCDates"));
    console.log($("#date").data('datepicker').getFormattedDate('yyyy/mm'));
}
<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-datepicker/1.8.0/js/bootstrap-datepicker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.css" rel="stylesheet"/>
<input type="text" id="date"><button onclick="getDates()">Get Dates</button>

To get the dates,

$("#date").datepicker("getDates") - Returns an array of selected start and end dates in local time.

$("#date").datepicker("getUTCDates") - Returns an array of selected start and end dates in UTC time.

$("#date").data('datepicker').getFormattedDate('yyyy/mm') - Returns the concatenation of start and end dates as strings formatted to the given format and joined by the multidateSeparator.

Upvotes: 1

Related Questions