sathish kumar sathish kumar - 4 months ago 17
Javascript Question

how to get days between two dates

I have 2 datepickers fr startdate and enddate.

1) For example, My startdate is "01/08/2016". And my end date is "06/08/2016".

2) I have selected (August 1 to august 6) total six days.

3) How can I get those days or print that all 6 days in a alert.

jsfiddle



var nowTemp = new Date();
var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
var checkin = jQuery('#startDate').fdatepicker({
format: "dd.mm.yyyy",
onRender: function (date) {
return date.valueOf() < now.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function (ev) {
}).data('datepicker');
var checkout = jQuery('#endDate').fdatepicker({
format: "dd.mm.yyyy",
onRender: function (date) {
return date.valueOf() <= checkin.date.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function (ev) {
checkout.hide();
}).data('datepicker');

jQuery("#startDate,#endDate").fdatepicker({
autoclose: true,
format: "dd.mm.yyyy",
language: 'de',
todayHighlight: false
});

<input type="text" id="startDate" name="start_datum" class="input_text date" value="" >

<input type="text" id="endDate" name="end_datum" class="input_text" value="">




Answer

You can use Date.prototype.getDate and Date.prototype.setDate:

var start = new Date('2016-07-31'),
  end = new Date('2016-08-06');

var date = start;
do {
  var date = new Date(date.setDate(date.getDate() + 1));
  console.log(date);
} while (date < end);

Comments