Javascript / Jquery - Calculation of days between two dates "DD / MM / YYYY" [duplicate]

2

Friends, good afternoon ... next, the code below, takes two dates in a calendar, in the format of

DD/MM/YYYY

$('.two-calendars').on('pickmeup-change', function (evt) {
	    var range = pickmeup(this).get_date('d-m-Y');
	    if (range[0] != range[1]) {
	        var label = pickmeup(this).get_date("d/m/Y");
	        $('.search-tool .periodo .field-title').text(label[0] + " até " + label[1]);
	       $('.search-tool .periodo input[name=periodo]').val(range);
			   $('.search-tool .periodo').addClass("checked");
			   $('.search-tool .periodo .header-title').html(range);
	    }

In the last line of the function, I did the following:

$('.search-tool .periodo .header-title').html(range);

To change one written in html, by the value of the range variable. The idea is to display the number of days between the two selected dates. I have tried, subtracting range[0] from range[1] , and hiding the months and years, but only works when the months are the same. I believe my doubt is more mathematical than programming. If you can help me, thank you.

Here is the code that I tried to do the subtraction:

$('.search-tool .periodo .header-title').html(range[0] - range[1]);

No prompt de comando it returns as illegal.

    
asked by anonymous 15.08.2018 / 19:58

3 answers

2

Initially, we should consider javascript to hold dates as a number that represents the number of milliseconds since January 1, 1970, so by taking that number of milliseconds from two different dates, we can make a difference between these values and divide them by the amount of milliseconds of a single day.

First, to find out the number of milliseconds of a day, we will multiply the number of hours, by minutes, by seconds, and finally by milliseconds:

const DAY = 24 * 60 * 60 * 1000;

Now, we'll need to create the two dates, which means entering your day, month, and year values to be created, and we can retrieve their values in milliseconds. The values I used are just an example, since the date should be passed like this:

var D1 = new Date(2017, 11, 24);
var D2 = new Date(2018, 07, 15);

var mlsD1 = D1.getTime();
var mlsD2 = D2.getTime();

Note: Please note that the dates refer to, respectively: December 24, 2017 and August 15, 2018. We need to pay attention in the month, which begins its count down to 0, so 0 refers to January, February and so on.

Now we need to calculate the difference between the two dates in milliseconds, so we will only subtract the most current date in milliseconds (mlsD2) by the oldest date (mlsD1):

var dif = mlsD2 - mlsD1;

Finally, to know this difference in days, we will only get this value and divide by the constant created at the beginning, which represents the number of seconds in a day:

var qtdDays = dif / DAY;

In this way we will have the number of days that passed between the two dates, not counting the initial day. To include the initial day we can add one to the result of the division or, if we only want the intermediate days, not counting the initial day and the end, just subtract one from the result obtained. I hope it's useful!

    
16.08.2018 / 02:36
1

As @Gabriel's answer , in fact with native JavaScript the only way is to do the accounts manually.

If you have no objections to using an external library, I recommend Moment.js , which facilitates handling and calculations with dates.

If your dates are in DD/MM/YYYY format, just parsing by String and its format.

For example, moment("30/01/2018", "DD/MM/YYYY") will create a date equivalent to January 30, 2018. Note that, other than the native JavaScrit, January here is month 1 - if you use new Date , as Gabriel's answer explains , January is month zero, so watch out at this point.

The "DD/MM/YYYY" format is described in documentation .

Then, to calculate the difference in days, just use diff . The code looks like this:

// 1 de janeiro de 2018
var inicio = moment("01/01/2018", "DD/MM/YYYY");
// 30 de janeiro de 2018
var fim = moment("30/01/2018", "DD/MM/YYYY");

// diferença entre as datas, em dias
var dias = fim.diff(inicio, 'days');
console.log(dias);
<script src="https://momentjs.com/downloads/moment.min.js"></script>

The result is 29 , since between 1 of January 30 the difference is 29 days.

    
16.08.2018 / 14:19
1

Below is an example of calculating the difference between dates, returning an integer in days.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

$('#calc').click(function(){
  var dt1 = $('#date1').val();
  var dt2 = $('#date2').val();
  
  $('#result').text(calcula(dt1,dt2))

});

function calcula(data1, data2){
  data1 = new Date(data1);
  data2 = new Date(data2);
  return (data2 - data1)/(1000*3600*24);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Subtrçãodasegundapelaprimeiradata:<hr><labelvalue="Primeira data: "><input id="date1" type="date">
<label value="Segunda data: "><input id="date2" type="date">
<input id="calc" type="button" value="Calcule">
<hr>
<label value="Resultado em dias:"><span id="result"></span>
    
16.08.2018 / 20:14