How to know if the chosen date is less than the current date?

Asked

Viewed 2,769 times

1

I need to issue an Alert if the chosen date 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 on the 15th and returned Minor.

That’s right

I put on the 16th did not return anything.

That’s right

I put on the 17th and returned Minor

You are wrong

I wish I knew where I was going wrong

  • Tried to take the toDateString and only compare purely the date?

  • If I take it off he accuses that counts the mileseconds

  • I adjusted my answer to remove time and compare

3 answers

4

Do not compare dates in format string using the toDateString. You can directly compare the date 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));

4


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

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.

  • I was already testing and I saw that I was counting the time.

  • @durtto altered to remove the time!

  • @Sorack, adding the time as it would

  • @Renanrodrigues takes a look at the issues. The first version considered the time.

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");
}

Browser other questions tagged

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