0

I am trying to compare two dates to see if one date is less than the other date, so I format both dates, then check if the expiry date is less than today and if it then show an alert message:

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; 

var yyyy = today.getFullYear();
if(dd<10){
          dd='0'+dd
} 
if(mm<10){
    mm='0'+mm
} 
var today = dd+'/'+mm+'/'+yyyy;

var ExpiryDate = result.VATExpiryDate;
var day = ExpiryDate.getDate();
 var month = ExpiryDate.getMonth()+1;
var year = ExpiryDate.getFullYear();
if(day<10){
      day='0'+day
} 
if(month<10){
      month='0'+month
} 
var ExpiryDate = day+'/'+month+'/'+year;

    if(ExpiryDate < today && result.VATAuthNo.length>0)
    {
          alert("Please note Vat Authorisation Date for " + result.Name + " has expired - " + ExpiryDate);
    }

But it seems it doesn't work for all dates. For example if the expiry date is 10/12/2015 it works and the alert message shows. But if the date is 21/06/2016 it doesn't work, even though that date is less than today.

user123456789
  • 1,914
  • 7
  • 44
  • 100

3 Answers3

2

You can compare dates operating directly with date object, not need to convert. javascript is a powerful language mate.

var today = new Date();
var expDate = new Date(2016, 10, 02)

if (today > expDate)
  alert("expired");
Jordi Flores
  • 2,080
  • 10
  • 16
0

Use the following method:

if( new Date(first).getTime() > new Date(second).getTime() ) {
  // code;
}

var date1 = new Date('2017-02-15');
var date2 = new Date('2017-02-15');

if( date1 === date2 ){
  console.log("bot are equal");
}
if( +date1 === +date2 ){
  console.log("bot are equal");
}
user7393973
  • 2,270
  • 1
  • 20
  • 58
0

You are comparing strings - to have correct results you shoud use format like YYYY-mm-dd not dd/mm/YYYY

Mateusz
  • 117
  • 1
  • 7