Search code examples
javascriptunix-timestamp

JavaScript: Compare 2 UNIX timestamps returns unexpected result


I need to compare 2 UNIX timestamps, one of them is token expire time (in future) and another is Date.now(). By some reason by comparing 2 timestamps it returns false result. It returns that validUntil is less than Date.now(). I cannot get why, googled but have not found any info.

var validUntil = 1629361800

// if validUntil is less than now, then token is expired

validUntil < Date.now()

// returns false, however, validUntil is greater than Date.now()

Solution

  • Date.now() returns number of milliseconds, not seconds... so you need to divide it by 1000 or multiply the other one by 1000.

    var validUntil = 1629361800
    validUntil * 1000 < Date.now()