Compare current date with javascript

I am comparing today's date with today's date like this:

if (new Date() > new Date('07/04/2017'))
{
     alert('Hoje é maior que hoje?')
}

How is it possible today to be greater than today?

Author: durtto, 2017-07-04

4 answers

As everyone has already said, the reason for this comparison is the time being used. If you want to compare only the dates, you can use the toDateString().

See the example below:

var hoje = new Date().toDateString();
var data2 = new Date('07/04/2017').toDateString();

console.log(hoje)
console.log(data2)

if (hoje > data2) {
  console.log('Hoje é maior que data2')
} else if (hoje == data2) {
  console.log('Hoje é igual a data2')
} else {
  console.log('Hoje é menor que data2')
}
 7
Author: Randrade, 2017-07-04 16:07:13

This is because new Date() also counts the current time, creating a date from the string the time is zeroed.

console.log(new Date());
console.log(new Date('07/04/2017'));

if (new Date() > new Date('07/04/2017'))
{
    console.log('Hoje é maior que hoje?')
}
 9
Author: LINQ, 2017-07-04 15:53:14

When you run new Date('07/04/2017') and assuming the formatting is accepted this will give the exact time at the start of that day, to the millisecond.

When you run only new Date() this will give the exact time at the time it is run, i.e. somewhere after the day has started.

If you split this into parts you can fix it better:

var inicio = new Date('07/04/2017');
var agora = new Date();

console.log('Diferença em milisegundos', agora - inicio);
console.log(
  'Diferença em h:m', [
    Math.floor((agora - inicio) / 1000 / 60 / 60),
    ':',
    Math.floor((agora - inicio) / 1000 / 60 % 60)
  ].join('')
); // 17h13m neste momento
 5
Author: Sergio, 2017-07-04 16:14:12

This comparison is correct because new Date() returns Tue Jul 04 2017 16:53:25 GMT+0100 (Hora de Verão de GMT) and new Date('07/04/2017') returns Tue Jul 04 2017 00:00:00 GMT+0100 (Hora de Verão de GMT)

If you repair the hours are different in the two uses of the date, because whenever you create a new "date" new Date() you are roughly creating a variable with the current month/day/year and hours-minutes-seconds.

If you create a date without specifying the hours new Date('04/04/2017'), The Hours-minutes-seconds value 0 will be assigned to this date.

You can also set the date with new Date('04/04/2017 01:00')

You can get the result what do you want with.

var d = new Date();
d.setHours(0,0,0,0);

if (d > new Date('07/04/2017'))
{
     alert('Hoje é maior que hoje?')
}
 4
Author: lazyFox, 2017-07-04 16:02:10