Subtract date from input with current date

5

I'm trying to subtract a date that the user types in 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 made these two blocks to put together the two dates, but I can not get through. I can not mount the current date to make a valid subtraction. I get wrong results.

    
asked by anonymous 17.08.2017 / 17:01

1 answer

2

See below an easy way to calculate difference using Math with methods abs() and ceil() .

  • Math.abs(x) : returns the absolute value of x , in 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, rescuing the current date using Date , 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 too, you can use the moment.js plugin. Here's 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>
    
17.08.2017 / 17:15