Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a Date datatype variable is in the past with Typescript?

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?

like image 323
Samantha J T Star Avatar asked Oct 14 '25 09:10

Samantha J T Star


2 Answers

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()

like image 70
Paul S. Avatar answered Oct 16 '25 22:10

Paul S.


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:

  • Compare two dates with JavaScript
  • JavaScript Date Object
like image 37
Radim Köhler Avatar answered Oct 16 '25 21:10

Radim Köhler