Compare current date with javascript

Asked

Viewed 19,332 times

6

I’m comparing today’s date to today’s date this way:

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

How can today be bigger than today?

  • I suppose the goal is to compare whether one date is longer than another, @Lucascosta

4 answers

9

That’s because new Date() also counts the current time, creating a date from the string time is zero.

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?')
}

8


As everyone has already said, the reason for this comparison is the time that is 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')
}

5

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

When you run only new Date() That will give the exact time at the moment it is run, or somewhere after the day has begun.

If you separate it into parts it might repair 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

  • 1

    and assuming that the formatting is accepted it will give the exact time at the beginning of that day, to the millisecond. All right Despite the answer to my question, Randrade’s answer gives me what I didn’t ask, but also what I need. Thank you.

4

That 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 repair the hours are different in the two uses of the date, because whenever it creates a new "date" new Date() roughly you are creating a variable with the current month/day/year and hours-minutes-seconds.

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

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

You can get the result 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?')
}

Browser other questions tagged

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