Skip to content Skip to sidebar Skip to footer

How To Detect If The Date Is In The Past Using Javascript?

I need to check if the date is in the past using javascript. The date format is like this: 10/06/2018 I can do this using the following code: var datep = '10/06/2018'; if(Date.pars

Solution 1:

Looking at the date constructor in the documentationsee "syntax", it expects integers in this order: YYYY,MM,DD,HH,MM,SS...

So reordering that is the trick. And remember that months are zero-based.

var date = '09/06/2018'; // DD/MM/YYYY// Create a date object...var dateArr = date.split("/");
var dateToCompare = newDate(parseInt(dateArr[2]),parseInt(dateArr[1])-1,parseInt(dateArr[0]));
console.log(dateToCompare);

// Date object for todayvar today = newDate();
console.log(today);

if(dateToCompare < today){
  alert('date is in the past');
}

Another way that I strongly suggest when it comes to deal with dates is the use of Moment.js:

So you can easilly manage any date format... And output a variety of date calculation reliably.

var date = '10/06/2018'; // DD/MM/YYYY// Create a date object...var dateToCompare = moment(date,"DDMMYYYY");  // See that second argument?console.log(dateToCompare);

// Date object for todayvar today = moment().startOf('day');  // At midnight earlier todayconsole.log(today);

if(dateToCompare < today){
  alert('date is in the past');
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

Solution 2:

Make it two numbers and compare

var date1 ='05/06/2018';
date1=parseInt(date1.split('/').reverse().join(''));
//number 20180605var date2 = newDate();
date2 = parseInt(date2.toISOString().slice(0,10).replace(/-/g,""));
// number 20180610//compareif(date1<date2)alert('in the past');

Post a Comment for "How To Detect If The Date Is In The Past Using Javascript?"