0

I have two sample unix timestamps that I'm trying to find the difference for in hours/minutes/seconds. One is a current time from TypeScript and one is an expiration time within 24 hours after. I just want to print out the time left until expiration.How do I go about this in TypeScript and Node?

current_time = 1633115367891
exp_time = 01633201203
Supez38
  • 329
  • 1
  • 3
  • 16
  • I think you have two different timestamp, one is in millisecond while other is unix timestamp. – Hassan Imam Oct 01 '21 at 19:28
  • Oh okay, I'm getting the expiration time from a package called JWT (json web token), https://www.unixtimestamp.com/ does display the correct time for both of them though. – Supez38 Oct 01 '21 at 19:32

1 Answers1

2

You can convert unix timestamp to milliseconds timestamp and take their delta. Then convert the delta to hh:mm:ss format.

const current_time = 1633115367891,
  exp_time = 1633201203,
  diff = (exp_time * 1000) - current_time,
  formatTime = (ms) => {
    const seconds = Math.floor((ms / 1000) % 60);
    const minutes = Math.floor((ms / 1000 / 60) % 60);
    const hours = Math.floor((ms / 1000 / 3600) % 24);
    return [hours, minutes, seconds].map(v => String(v).padStart(2,0)).join(':');
  }
console.log(formatTime(diff));
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51