Subtract input date with current date

Asked

Viewed 846 times

5

I am trying to subtract a date that the user type 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 set up these two blocks to assemble the two dates, but I can’t get past here. I am unable to mount the current date to make a valid subtraction. I get wrong results.

  • You want to calculate the difference?!

  • 1

    Yes. The difference in days.

1 answer

2


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

  • Math.abs(x) : returns the absolute value of x, in which the difference in dates is calculated using the getTime.
  • 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 by 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, you can also use the plugin Moment.js. 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>

Browser other questions tagged

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