Compare two dates and times and check if one is larger than the other typescript

Asked

Viewed 1,407 times

0

I created a function that receives an account, I need to check if a property conta.venc_token is longer than today’s date, if it is, return true(because it is an invalid token), otherwise return false.

I tried that way:

  verificaVenceuConta(conta):boolean{
    var data = conta.venc_token
    console.log(data);
    console.log(new Date())
    if(data > new Date()){
      console.log("entrou no if")
      return true
    }else{
      console.log("entrou no false")
      return false
    }
  }

But the format that returns from my backend is very different from the format that javascript generates the current date.

Us console.log I have:

Format of my backend:

10/04/2019 18:27:38

Format that javascript generates:

Wed Apr 10 2019 14:28:55 GMT-0300 (Horário Padrão de Brasília)

I would like to know a way to compare. This way I found can correctly compare dates and times? By the tests I’ve done always returns in else (false).

  • If console.log(data); prints 10/04/2019 18:27:38, is probably a string (which you should convert to Date) - check out typeof(data) just to be sure. Because when printing a Date, it is always shown in this format "Wed Apr 10 etc...". Another detail is to know if 18:27 is in the same time zone as the frontend, otherwise there is no way to make the conversion reliably.

  • Yeah, it’s kind of string

2 answers

2


The most practical way I know to convert text to date is by referencing Moment js.

moment().format('YYYY-MM-DD HH:m:s'); 

moment("20111031", "YYYYMMDD").fromNow();

moment("20120620", "YYYYMMDD").fromNow();

moment().startOf('day').fromNow();       

moment().endOf('day').fromNow();         

1

I got it that way:

  verificaVenceuConta(conta):boolean{

    var partesData = conta.venc_token.split("/")
    partesData[1] = partesData[1] - 1;
    partesData[2] = partesData[2].substring(0,4)
    partesData.push(conta.venc_token.substring(11,19))
    partesData[3] = partesData[3].split(":")
    let dataMontada = new Date(partesData[2], partesData[1], partesData[0], partesData[3][0], partesData[3][1], partesData[3][2])

    if(dataMontada < new Date()){
      return true
    }else{
      return false
    }

  }

It’s not very attractive, but it was the easy way I managed without using frameworks

  • 1

    Don’t forget that in Javascript months are indexed to zero (January is zero, February is 1, etc), so you have to subtract 1 of the month before going to the constructor Date :-)

  • 1

    thanks for the comment, I will do here

Browser other questions tagged

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