Convert String to Date and check if it is a valid Javascript date

Asked

Viewed 305 times

0

I’m trying to turn a number into a date, for example:

Step by string: '00260030062016'

I need to get the latest numbers 30062016 and turn into date 30/06/2016. After that, I need to check if this date is valid.

I tried to use:

verificarData(numero) {
      const dataNumero = new Date(numero.substring(6, 14));
      console.log(dataCertificado);
  }

But he returns to me Invalid date. Will I have to use splits for this and concatenate with "/" to then turn into a date?

I used Date.parse() but he did call me back NaN.

1 answer

4


The builder of Date does not accept any string in any format. In this case, the string 30062016 in fact it is not accepted. And call Date.parse with the same string does not help, because so much parse how much the constructor accepts the same formats.

See in the documentation the formats that are accepted. Any format other than what is there can or not working, depending on the implementation of each browser (see here an example where a specific format gives difference between browsers).

Anyway, one way to check whether the date is valid is to extract the snippets you need and convert them to numbers by passing them to the Date:

function dataValida(s) {
    let dia = parseInt(s.substring(6, 8));
    let mes = parseInt(s.substring(8, 10)) - 1;
    let ano = parseInt(s.substring(10));
    if (isNaN(dia) || isNaN(mes) || isNaN(ano)) return false;

    let d = new Date(ano, mes, dia);
    return dia == d.getDate() && mes == d.getMonth() && ano == d.getFullYear();
}

[ '00260030062016', '00260032012019', '00260030xy2016'].forEach(s => {
  console.log(`${s} válido? ${dataValida(s) ? 'sim' : 'não' }`);
});

I use parseInt to convert each chunk to number. If any of them are not number, the function already returns false, because it is not a date.

I had to subtract 1 of the month because in Javascript the months are indexed to zero (January is zero, February is 1, etc - see here for more details).

Then I create the date and check if the values of the day, month and year are the same that I got from the string. This may sound strange, but if you create a date on January 32nd, for example, the Date adjusts to February 1. Then if the values returned by getters are different, you know some invalid value has been passed.

Browser other questions tagged

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