If you want to compare the date and time, but ignoring the seconds, an alternative is to use the method setSeconds
and change the value of seconds to zero.
I recommend also change the milliseconds, so you ensure that only hours and minutes will be considered:
// uma data qualquer
var d = new Date();
// mudar segundos e milissegundos para zero
d.setSeconds(0);
d.setMilliseconds(0);
console.log(d);
Do this with the two dates you want to compare (data_publicacao
and data_atual
), so you make sure that the seconds (and fractions of a second) will not interfere with the comparison.
To compare them, no use >
and <
(nor any other operators) directly, because it doesn’t always work (if I’m not mistaken, in some browsers it may work, but it’s not guaranteed to work at all). The best is use the value returned by getTime()
, which returns the numerical value of Unix timestamp (the number of milliseconds since 1970-01-01T00:00Z).
So your if
would look like this:
if (data_publicacao.getTime() > data_atual.getTime()
|| data_publicacao.getTime() < data_atual.getTime()) {
Just one detail, this if
means: if the publication date is longer than the current date (ie in the future) or if the publication date is less than the current date (ie in the past).
If the publication date is in the past or future, you want to enter if
, is that right? I mean, any date other than the current one will enter this if
.
Anyway, this is a way to disregard the seconds in the comparison. I would just revise the criterion of if
, 'Cause it’s kind of weird for me...
Whenever I need to work with dates, when possible I use the library momentjs who has methods to facilitate this
– Ricardo Pontual
The dates to compare would be what? Days, months, years?
– LeAndrade
What I usually do is take . getDate(), . getMonth(), and . getFullYear(), and insert within the date, so it generates only the day month and year, while the time is always 00:00:00. Anyway, I don’t know if it’s considered to you to pollute the code.
– Máttheus Spoo
Ricardo -> I’ll give a search
– Arthur Gabriel Silva Arantes
Leandrade -> It would be the date and time
– Arthur Gabriel Silva Arantes
Máttheus -> I get it, I don’t like it, I need the time
– Arthur Gabriel Silva Arantes
well, if you don’t mind writing, just add getHours() and getMinutes(). It will only take more work, but it works.
– Máttheus Spoo
But how do I put all these methods into a variable? it does not accept dateAtual.getDate(). getMonth()...
– Arthur Gabriel Silva Arantes
like I said, if you don’t mind polluting your code, you can do
var a = new Date();
and thenvar dataAtual = new Date(a.getFullYear(), a.getMonth(), a.getDate(), a.getHours(), a.getMinutes());
– Máttheus Spoo
Guy in your case there is as Matheus said, it will have to get big code, javascript is kind of boring to work with date. Or you take it all with the new date() or separates by methods getHours(), getMinutes(). You choose.
– LeAndrade