Problem with date comparison in Javascript

Question:

I have a function in Javascript that is to check if the "current_date" is greater than the "expiration_date". If it is bigger, it is to display the text "Expired" on the screen, if not, it keeps the text "Valid".

What's the problem? The function is only considering the day of the expiration date, not the month and year . If the expiration day is greater than the current day, it displays "Valid", even if the expiration year is 2010 for example. I believe the problem may have some relationship because the validity is in text format, in a database like Varchar.

Here is an example of the code: https://jsfiddle.net/ec0nugyq/

 var data_validade = '20/03/2010'; // Simula a data de validade do banco de dados (VARCHAR) var data_atual = moment(new Date()).format('DD/MM/YYYY'); // Captura a data atual no formato brasileiro - Ex: 14/03/2021 if (data_atual > data_validade) { document.write('Expirado'); // Se a data atual for maior que a validade, exibe Expirado na tela } else { document.write('Válido'); // Se a data atual for maior que a validade, exibe Válido na tela }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

If anyone knows how to solve this in a simple way, I really appreciate it!

Answer:

It should be noted that the Moment.js library in its documentation discourages developers from including Moment.js in new projects.
The reasons for this are stated in the library's documentation.

As for the problem at hand this can be easily solved using the native JavaScript Date object.

 //Prepara a data para ser usada como argumento do constructo Date. let data = '20/03/2010'.split("/").reverse(); //Separa os componentes da data e os coloca na ordem ano, mês e dia para ser consumida pelo constructor Date(ano, mês, dia). data[1]--; //Reduz em uma unidade o mês pois o constructor Date trabalha com meses de 0 até 11 onde mês 0 é janeiro. let data_validade = new Date(...data); let data_atual = new Date(); if (data_atual > data_validade) { document.write('Expirado'); } else { document.write('Válido'); }

The main problem with your code is that in:

if (data_atual > data_validade)

You are comparing two strings because at some point some data_atual was converted to an object that models time/dates and data_validade is the string representation of the current date obtained with moment(new Date()).format('DD/MM/YYYY'); . So your comparison only compares the characters of the two strings and not the dates themselves.

To fix the problem, it was enough to work only with Date objects. To convert the string 20/03/2010 into a consumable form by constructor new Date(ano, mês, dia, hora, minuto, segundo, milissegundo); the string was split into its components using the String.prototype.split() method which splits a String into an ordered list of sub-strings and returns them in an Array [dia, mês, ano] and then inverted with the Array.prototype.reverse() method Array.prototype.reverse() so that the format is consumed by the constructor new Date(ano, mês, dia, hora, minuto, segundo, milissegundo); . Then the month suffered a decrement of one unit as the date builder operates with the month starting from 0 for January to 11 for December. This is so that the array containing the date can be consumed by the constructor new Date(ano, mês, dia, hora, minuto, segundo, milissegundo); using the spreading syntax using only the first three parameters.
Apart from the aforementioned, the rest of the code remains the same.

For ease of use a function can be created that converts the string in dd/mm/YYY format into a Date object here called ptBRStringToDate(s) where s is a string containing the date.

 function ptBRStringToDate(s) { let data = s.split("/").reverse(); data[1]--; return new Date(...data); } let listaDatas = ["10/03/2020", "10/03/2021", "10/03/2022"] let data_atual = new Date(); for (let d of listaDatas) { let data_validade = ptBRStringToDate(d); document.write(`${d}: ${(data_atual > data_validade)? 'Expirado':'Válido'}<br>`); }
Scroll to Top
AllEscort