How do I know if the chosen date is smaller than the current date?

1

I need to issue an alert if the date you choose is less than the current date. I did so:

var strData = "15/08/2017";
var partesData = strData.split("/");
var data = new Date(partesData[2], partesData[1] - 1, partesData[0]).toDateString();
if(data < new Date().toDateString())
{
   alert("Menor");
   }

I put day 15 and returned Minor.

  

That's right

I put day 16 did not return anything.

  

That's right

I placed Day 17 and returned Minor

  

You're wrong

I wonder where I'm going wrong

    
asked by anonymous 16.08.2017 / 22:15

3 answers

4

Remove toDateString in comparison, otherwise you will be comparing Strings value:

comparar("17/08/2017");
comparar("16/08/2017");
comparar("15/08/2017");

function comparar(strData) {
  var partesData = strData.split("/");
  var data = new Date(partesData[2], partesData[1] - 1, partesData[0]);
  var hoje = new Date();

  hoje = new Date(hoje.getFullYear(), hoje.getUTCMonth(), hoje.getUTCDate());

  if (data < hoje) {
    console.log(strData, "Menor");
  }
}

I performed the conversion by removing the time options by creating a new date.

    
16.08.2017 / 22:21
4

Do not compare dates in string format using toDateString . You can directly compare the data object:

function comparar(string) {
  var d = string.split("/");
  var data = new Date(d[2], d[1] - 1, d[0]);
  var agora = new Date();
  return data > agora ? 'maior' : 'menor';
}

console.log(["10/08/2017", "15/12/2317"].map(comparar));
    
16.08.2017 / 22:19
0

Simplest form

var strDate = "15/08/2017".split('/').reverse();
//Saida -> ["2017", "08", "15"]

//Data em milisegundos 
var currentDate = new Date(strDate).valueOf();
//Data atual em milisegundos 
var dateNow = new Date().valueOf();

if(currentDate < dateNow)
{
   alert("Menor");
}
    
17.08.2017 / 06:56