-1

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.parse(datep)-Date.parse(new Date()) < 0) {
   alert('date is in the past');
}

But this code seems to only check for Year. So if the Month or the Day is in the past, it will ignore that!

Could someone please advice on how to check for the day and month as well as the year?

Thanks in advance.

EDIT:

The date format is

dd/mm/yyyy 
Rooz Far
  • 187
  • 1
  • 3
  • 11

2 Answers2

1

Looking at the date constructor in the documentation see "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 = new Date(parseInt(dateArr[2]),parseInt(dateArr[1])-1,parseInt(dateArr[0]));
console.log(dateToCompare);

// Date object for today
var today = new Date();
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 today
var today = moment().startOf('day');  // At midnight earlier today
console.log(today);

if(dateToCompare < today){
  alert('date is in the past');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
  • Not working for me. `var date = '10/06/2018'` gives me _date is in the past_. And today defenitely is the 10th :-) – Michel Jun 10 '18 at 16:08
  • That is because `today` should be named now... It include the actual time in the day. And the date to compare is like at midnigth in the beginning of the day. Look at the console.logs – Louys Patrice Bessette Jun 10 '18 at 16:10
  • You are correct, but OP is asking if the DATE is in the past. Not date + time. – Michel Jun 10 '18 at 16:11
0

Make it two numbers and compare

var date1 ='05/06/2018';
date1=parseInt(date1.split('/').reverse().join(''));
//number 20180605

var date2 = new Date();
date2 = parseInt(date2.toISOString().slice(0,10).replace(/-/g,""));
// number 20180610

//compare
if(date1<date2)alert('in the past');
Michel
  • 4,076
  • 4
  • 34
  • 52
  • This is completely unnecessary. The Date API completely covers this use case without the need for string parsing and other similar hacks. – Pointy Jun 10 '18 at 23:21