4

I have this function:

   isAuthenticationExpired = (expirationDate: Date) => {
        var now = new Date();
        if (expirationDate - now > 0) {
            return false;
        } else {
            return true;
        }
    }

Both expirationDate and now are of type Date

Typescript give me an error saying:

Error   3   The left-hand side of an arithmetic operation must be of type 
'any', 'number' or an enum type.    

Error   4   The right-hand side of an arithmetic operation must be of type 
'any', 'number' or an enum type.    

How can I check if the date has expired as my way does not seem to work?

Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427

2 Answers2

6

Get the integer value representation (in ms since the unix epoch) of the Date now and expirationDate using .valueOf()

var now = new Date().valueOf();
expirationDate = expirationDate.valueOf();

Alternatively, use Date.now()

Paul S.
  • 64,864
  • 9
  • 122
  • 138
2

The standard JS Date object comparison should work - see here

module My 
{
    export class Ex 
    {
        public static compare(date: Date)
            : boolean
        {
            var now = new Date();       
            var hasExpired = date < now;
            return hasExpired;
        }
    }
}

var someDates =["2007-01-01", "2020-12-31"]; 

someDates.forEach( (expDate) =>
{
    var expirationDate = new Date(expDate);
    var hasExpired = My.Ex.compare(expirationDate);

    var elm = document.createElement('div');
    elm.innerText = "Expiration date " + expDate + " - has expired: " + hasExpired;    
    document.body.appendChild(elm);
});

More info:

Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335