Selected date comparison with the current date JS

5

I've already searched the internet and right here on the site, but I could not find any clean and working way to do that.

I need JS to compare the date in the field (which will be in a DD / MM / YYYY format) and compare with the current date if the date indicated is greater than the current date of an alert.

    
asked by anonymous 12.05.2015 / 17:01

3 answers

13

You can convert your date from String to Date and compare with the operator:

var strData = "28/02/2015";
var partesData = strData.split("/");
var data = new Date(partesData[2], partesData[1] - 1, partesData[0]);
if(data > new Date())
   alert("maior");

Remarks :

  • In Javascript, instantiating a new object Date with the empty constructor ( new Date() ) results in an object representing the current date / time.

  • The second parameter of the constructor of class Date is the month, which is indexed from 0 to 11. Therefore, you must subtract 1 from the date value in string.

12.05.2015 / 17:30
3

I believe that if you invert the order JavaScript already parse:

.split('/').reverse().join('/');

jsFiddle: link

var str = "28/02/2020";
var date = new Date(str.split('/').reverse().join('/'));
var novaData = new Date();
if(date > novaData) alert("Essa data ainda não chegou!");
    
12.05.2015 / 17:57
3

Although they have already replied, use another isAfter() of Momentjs which is a Javascript library for handling and handling dates.

// 12/05/2015 é depois de 01/05/2015?
if(moment('2015-05-12').isAfter('2015-05-01'))
    alert("Yep!");
<script src='http://momentjs.com/downloads/moment.min.js'></script>
    
12.05.2015 / 18:29