Subtract date with javascript

Asked

Viewed 1,519 times

1

I have the following problem, I have a date that comes from the bank and I compare with the current date, and I do the following:

var dataAtual = new Date();
var partesData = dataAtual.split("/");
var dataAtualNova = new Date(partesData[2], partesData[1] - 1, partesData[0]);
var dataassinado = new Date({vem do banco});

if(dataAtualNova < dataassinado){ //faça algo }

But the current date is for example 17/05/1995 and date coming from the bank 17/05/1995 10:45 then if the dates are equal to the date coming from the bank will always be longer than the current date because of the hours, as I can match or take the hours?

  • 4

    Hey, buddy, you ever think about using Moment js.? Maybe I’d consider using it more.

  • Nice friend, but for this problem I would like to use pure jquery or js

2 answers

3


Using javascript only

  • Use the method Date.setHours(0, 0, 0, 0) - passing zero to the constructor to reset the hours
  • To compare dates, use the method Date.getTime() that will return an integer with the total of milliseconds of the date.

var data1 = new Date(2016, 11, 1, 16, 15, 30); // 01/12/2016 16:15:30
var data2 = new Date(2016, 11, 1); // 01/12/2016 00:00:00

console.log('Comparando com as horas, elas são diferentes:');
console.log(data1.getTime() === data2.getTime());

data1.setHours(0, 0, 0, 0);

console.log('Sem as horas, são iguais.');
console.log(data1.getTime() === data2.getTime());

  • 1

    That’s what I needed, thank you :)

2

If the date you have is in this format 17/05/1995 10:45, you can separate by space and pick up only the date:

var somenteData = "17/05/1995 10:45".split(" ")[0]; // 17/05/1995 10:45 > 17/05/1995
  • 1

    Thanks for the help, the friend data1.setHours(0, 0, 0) command above satisfied me

Browser other questions tagged

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