Home > Mobile >  Find difference between two unix timestamps that are within 24 hours in TypeScript and Node
Find difference between two unix timestamps that are within 24 hours in TypeScript and Node

Time:10-02

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

CodePudding user response:

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

  • Related