javascript – Subtract coming date from input with current date

Question:

I'm trying to subtract a date the user types into the input with the current date.

 var data1 = $("#data_viagem").val();
 var data1 = data1.split("/");
 var viagem = new Date(data1[2], data1[1], data1[0]);

 var dateObj = new Date();
 var month = dateObj.getUTCMonth() + 1; //months from 1-12
 var day = dateObj.getUTCDate();
 var year = dateObj.getUTCFullYear();

I set up these two blocks to set up the two dates, but I can't get past here. I'm not able to mount the current date to make a valid subtraction. I get wrong results.

Answer:

Below is an easy way to calculate difference using Math with the abs() and ceil() methods.

  • Math.abs(x) : returns the absolute value of x , on which the difference of dates is calculated using the getTime method.
  • Math.ceil(x) : returns the smallest integer greater than or equal to x .
var date1 = new Date("05/05/2017");
var date2 = new Date("08/17/2017");

var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
console.log(diffDays+ " dias");

Adapting to your case, retrieving the current date using Date , it would look something like this:

var dataAtual = new Date();
var dd = dataAtual.getDate();
var mm = dataAtual.getMonth()+1; //Janeiro é 0!
var yyyy = dataAtual.getFullYear();

if(dd<10) {
    dd = '0'+dd
} 

if(mm<10) {
    mm = '0'+mm
} 

dataAtual = mm + '/' + dd + '/' + yyyy;
console.log(dataAtual);

var date1 = new Date("05/05/2017");
var date2 = new Date(dataAtual);

var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
console.log(diffDays+ " dias");

If you prefer, you can also use the moment.js plugin. See how easy it can be:

var viagem = moment("05/05/2017", "MM/DD/YYYY");
var dataAtual = moment(moment(), "MM/DD/YYYY");
var diffDays = dataAtual.diff(viagem, 'days');

console.log(diffDays+" dias");
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>

<div id='result'></div>
Scroll to Top