String to date.parse Javascript conversion problem

Asked

Viewed 126 times

3

I’m getting in a date value variable on string and making the conversion to date, to be able to make a condition. The problem is that when the date comes as 31/12, the variable gets NaN. Follow the example below:

function ValidaDataVersao(escopoGrade)
{
    debugger;   
    dataInicial = Date.parse(escopoGrade.registroSelecionado.DataInicial);
    dataFinal = Date.parse(escopoGrade.registroSelecionado.DataFinal);
    let sequenciaValida = true;

    if (dataInicial > dataFinal) {
                smartBox.Alerta(null,
                    'Cancelado!',
                    "Data Inicial deve ser menor que Data Final.",
                    6000);

                sequenciaValida = false;
                return false;
        }
    return sequenciaValida;
}
let escopoGrade = angular.element('#gradePerfilECDVersoes').scope();

if (escopoGrade)
{
    escopoGrade.adicionarCriticas(function () { 
        return ValidaDataVersao(escopoGrade); 
    });
}

If the date comes on string for 31/12/2020, for example the variable is as NaN and then I can’t make the comparison.

3 answers

2

I was able to solve by searching. The solution was to break through Split transforming into Array and then give a new date. It was like this:

        function ValidaDataVersao(escopoGrade)
        {
            let dataInicialArray = escopoGrade.registroSelecionado.DataInicial.split("/");
            let dataInicial = new Date(dataInicialArray[2], dataInicialArray[1]-1, dataInicialArray[0]);

            let dataFinalArray = escopoGrade.registroSelecionado.DataFinal.split("/");
            let dataFinal = new Date(dataFinalArray[2], dataFinalArray[1]-1, dataFinalArray[0]);

            let sequenciaValida = true;

            if (dataInicial > dataFinal) {
                        smartBox.Alerta(null,
                            'Cancelado!',
                            "Data Inicial deve ser menor que Data Final.",
                            6000);

                        sequenciaValida = false;
                        return false;
                }
            return sequenciaValida;
        

1

You can’t make a Date.parse of an invalid date. A documentation mozilla says that:

The Date.parse() method analyzes a data representation in string, and returns the number of milliseconds since 1 January 1970, 00:00:00 UTC or Nan if the string is not recognized or, in some cases, contains invalid date values (e.g. 2015-02-31).

As help, I leave a script that I use for creating and formatting dates:

const options = { year: "numeric", month: "long", day: "numeric" };
const date = new Date(2020, 11, 31) // 2020-12-31T03:00:00.000Z
console.log(date.toLocaleDateString("pt-br", options))
// 31 de dezembro de 2020
console.log(date.toLocaleDateString("pt-br", { ...options, month: 'numeric'}))
// 31/12/2020

1


According to the documentation, the only format that is guaranteed to work the same way in all browsers (described here) is based on the standard ISO 8601 (in his example, it would be "2020-12-31"). Any other format is not guaranteed, because the same documentation quotes:

If the String does not conform to the standard format the Function may Fall back to any implementation-specific heuristics or implementation-specific Parsing Algorithm. Unrecognizable strings or Dates containing illegal element values in ISO Formatted strings Shall cause Date.parse() to Return Nan.

That is, any format other than ISO 8601 may or may not work depending on the implementation (browser version or the engine - Node, Deno, etc), even if the string is a valid date in some contexts - "31/12/2020" may or may not be valid, because in the American format, for example (month/day/year) it is invalid, although it is valid in other countries.

The fact is that, because it is not in ISO 8601 format, it is not guaranteed to work (for example, in Chrome, "12/31/2020" works, but "12/31/2020" does not, which indicates that it interprets this date as being in American format).

Anyway, in this case there’s not much of a way but to break the string into pieces and build the date manually:

let s = "31/12/2020";
let [dia, mes, ano] = s.split("/");
let data = new Date(ano, mes - 1, dia);
console.log(data);

Remembering that I had to subtract 1 of the month, because no Date months are indexed to zero (January is zero, February is 1, etc).


Another option, if you can add a lib external, is to use the Moment js.:

// converte a string para data, o formato DD/MM/YYYY indica como fazer o parsing corretamente
let m = moment("31/12/2020", "DD/MM/YYYY");
// converter para Date
let data = m.toDate();
console.log(data);

// para comparar com outra data, não precisaria converter para Date
let m2 = moment("28/12/2020", "DD/MM/YYYY");
if (m.isAfter(m2)) console.log('m é depois de m2');
<script src="https://momentjs.com/downloads/moment.min.js"></script>


To learn more about the subject, read here, here, here, here, here, and here.

  • 1

    Congratulations bro! That was the only way it even worked. Thanks.

Browser other questions tagged

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