Comparison of dates in Javascript

Asked

Viewed 187 times

-1

Hello I need to compare the current date with the one typed by the user but the seconds prevent this verification:

var data_publicacao = new Date($('#frm-data').val());
    console.log(data_publicacao);
    var data_atual = new Date();
    console.log(data_atual);
    if (data_publicacao != undefined) {
        if (data_publicacao > data_atual || data_publicacao < data_atual) {
            alert("Sua notícia foi salva, mas ainda não foi publicada! Aguarde.");
        }
        else {
            noticias.push(noticia);
            atualizarLista(noticia);
            alert("Notícia publicada!");
        }
    }

Is there any way to take the seconds easily without leaving the code polluted?

  • 2

    Whenever I need to work with dates, when possible I use the library momentjs who has methods to facilitate this

  • 1

    The dates to compare would be what? Days, months, years?

  • 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.

  • Ricardo -> I’ll give a search

  • Leandrade -> It would be the date and time

  • Máttheus -> I get it, I don’t like it, I need the time

  • well, if you don’t mind writing, just add getHours() and getMinutes(). It will only take more work, but it works.

  • But how do I put all these methods into a variable? it does not accept dateAtual.getDate(). getMonth()...

  • like I said, if you don’t mind polluting your code, you can do var a = new Date(); and then var dataAtual = new Date(a.getFullYear(), a.getMonth(), a.getDate(), a.getHours(), a.getMinutes());

  • 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.

Show 5 more comments

3 answers

1

toLocaleDateString() - date only string in the format located on your system.

var data_atual = new Date();

console.log(data_atual.toLocaleDateString());

What you want is given in the @hkotsubo reply

I’ll chew for you!

var data_publicacao = new Date($('#frm-data').val());
data_publicacao.setSeconds(0);
data_publicacao.setMilliseconds(0);
data_publicacao = (data_publicacao.getTime());

var data_atual = new Date();
// mudar segundos e milissegundos para zero
data_atual.setSeconds(0);
data_atual.setMilliseconds(0);
data_atual = (data_atual.getTime());
    
if (data_publicacao > data_atual || data_publicacao < data_atual) {
.....
    
  • but ae it does not take the time, need the date and time to meet the demands of the activity :/

  • Good to know. Now comes the question. If it turns the date into a string, how can it compare whether one date is longer or smaller than the other if they are strings and not dates?

  • Pse I got this doubt in class, the teacher says that even passing to string he makes the comparison(??), now how is it made he did not tell me...

1


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...

-1

I got find the answer on Github, follow the instructions:

<script src="https://rawgit.com/Lautert/helpers/master/javascript.helpers.js"></script>

var d = new Date();
console.log(d.toDate('dd/mm/yyyy hh:ii:ss'));

console.log(d.toDate('mm/dd/yyyy hh:ii:ss'));

console.log(d.toDate('yyyy-mm-dd'));

console.log(d.toDate('yyyy-dd'));

Browser other questions tagged

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