Javascript/Jquery - Calculating days between two "DD/MM/YYYY" dates

Asked

Viewed 3,885 times

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 tried, subtract the range[0] for range[1], and hide the months and years, but it only works when the months are equal. I believe my doubt is more mathematical than about programming. If you can help me, I’d appreciate it.

Here’s the code I tried to subtract:

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

In the prompt de comando he returns as illegal.

  • 3

    Here’s your answer: https://answall.com/a/86768/11482

3 answers

2

Below is an example of a calculation of 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ção da segunda pela primeira data:
<hr>
<label value="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>

  • 1

    bro! fuck this example you did, Rigadão ai, helped me a lot to understand better how it works in practice.

  • 1

    Luiz, I have a question, I don’t know if you can help me...

  • 1

    but so I can get a 2018-08-23 date... but if I happen to work with a "DD-MM-YYYY" date format I would have to do an algorithm to change the order of the values, or would the calculation also work? Because the tests I did at the command prompt, I can only calculate in the format "YYYY-MM-DD" I thank you from now on!

2


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

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

const DAY = 24 * 60 * 60 * 1000;

Now, we will need to create the two dates, which implies entering their values of day, month and year so that they are created and we can recover their values in milliseconds. The values I used serve only as an example, given that the date should be passed in this way:

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

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

Note that the dates refer to, respectively: December 24, 2017 and August 15, 2018. We need to pay attention in the month, which begin their count at 0, so 0 refers to January, 1 to February and so on.

We need to calculate now the difference between the two dates obtained in milliseconds, for this 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 take this value and divide it by the constant created at the beginning, which represents the amount of seconds in a day:

var qtdDays = dif / DAY;

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

  • 1

    Bro, seriously... thank you so much for explaining everything so fucked up so... because it gave me a fucking sense of how it works... I’ll try to do it here using this logic! Brigadão!

  • 1

    I had tried to use the link logic of another question that the boy posted above, only that, I was trying to do the direct calculation, and I wasn’t going. found a lot more fuck this way, like a variable with the calculation.

1

In accordance with the reply from @Gabriel, 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., that facilitates much handling and calculations with dates.

If your dates are in format DD/MM/YYYY, just do the Parsing by going to String and its format.

For example, moment("30/01/2018", "DD/MM/YYYY") will create a date equivalent to January 30, 2018. Note that, unlike native Javascrit, here is January 1 - if you use new Date, in accordance with Gabriel’s response explains, January is month zero, so watch this point.

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

Then, to calculate the difference in days, just use diff. The code goes 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, as between 1 from 30 January the difference is 29 days.

  • 1

    mano, you commented a stop dahora... because I was trying to calculate, then when I gave a "typeof" in the command, it returned as string, and there is no way to calculate string, so I would give "Nan"... I have no problem in using external library ahhahaha I will put the link even. vlw for the help

Browser other questions tagged

You are not signed in. Login or sign up in order to post.