Selected date comparison with current JS date

Asked

Viewed 32,528 times

10

I’ve searched the internet and right here on the site, but could not find any clean way and that works to do this.

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

  • tries to transform the two dates of DD/MM/YYYY to YYYYMMDD (without / and in order) and make the comparison normally YYYYMMDD > YYYYMMDD

3 answers

23


You can convert your date from String for 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, instantiate a new object Date with the empty constructor (new Date()) results in an object representing current date/time.

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

  • 1

    It worked perfectly partner! Thank you!

  • 2

    information about the builder new Date(), the second parameter (month) is indexed in 0, or goes from 0 to 11, so the -1

  • Good, I forgot to comment on the reply. I will edit.

3

I believe that if you reverse the order Javascript already parse:

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

jsFiddle: http://jsfiddle.net/wfpzu1s5/

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

3

Although already answered, follows another way using the function isAfter() of Momentjs which is a Javascript library for date handling and manipulation.

// 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>

Browser other questions tagged

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