I'm comparing today's date with today's date like this:
if (new Date() > new Date('07/04/2017'))
{
alert('Hoje é maior que hoje?')
}
How can today be greater than today?
I'm comparing today's date with today's date like this:
if (new Date() > new Date('07/04/2017'))
{
alert('Hoje é maior que hoje?')
}
How can today be greater than today?
As everyone has already said, the reason for this comparison is the time that is being used. If you want to compare dates only, you can use 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')
}
This is because new Date()
also counts the current time, creating a date from string the time is set to 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?')
}
When you run new Date('07/04/2017')
and assume that the formatting is accepted this will give the exact time at the start of that day, in millisecond.
When you run only new Date()
this will give the exact time at the time it is run, ie somewhere after the day has started.
If you separate this into parts you can repair 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
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 times differ in the two uses of the date, since whenever you create a new date new Date()
roughly you are creating a variable with the current month / day / year and hour-minutes-seconds.
If you create a date without specifying the hours new Date('04/04/2017'
) will be assigned to this date the hours-minutes-seconds the 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?')
}