E
E
EvgenyKabakov2022-03-19 14:41:17
JavaScript
EvgenyKabakov, 2022-03-19 14:41:17

How to get difference between two dates in days and hours in datetimepicker plugin?

Good day to all! Please help with this question:
The site uses the datetimepicker plugin to select the rental start date and end date,
you can select dates and exact times.
You need to get the difference between the two selected dates in the number of days and in the exact number of hours.
The number of days seems to be calculated, but the number of hours does not work.
There is such a code:

$("#startdate").datetimepicker({
  minTime: 0,
  minDate: date
});
$("#enddate").datetimepicker({
  minTime: 0,
  minDate: date
});

$('#enddate').change(function() {
  var startDate = $('#startdate').datepicker('getDate');
  var endDate   = $('#enddate').datepicker('getDate');
                
  if (startDate < endDate) {
    var dayDiff = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24));
    console.log(dayDiff);
    var hoursDiff = (dayDiff * 24) / 60;
    console.log(hoursDiff);
  } else {
    alert ("Извините, нельзя выбрать дату окончания аренды ранее даты начала аренды");
    $('#enddate').val("");
    $('#days').val("");
  }
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2022-03-19
@EvgenyKabakov

First get the difference between two Date objects in hours.
Then see how many whole days fit into these hours, and subtract them.

const diffHours = Math.ceil((endDate - startDate) / 36e5); // точно в бОльшую сторону округлять?
const days = Math.floor(diffHours / 24);
const hours = diffHours - days * 24;

console.log(`Срок аренды: ${days} дней и ${hours} часов`);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question