0

How can I extract time only as a unix number from a unix timestamp? For example:

const timeStamp = 1671682809 // Thursday, December 22, 2022 11:20:09 AM GMT+07:00
const unixTimeOnly = extractTime(timeStamp) // return a unix number that represents "11:20:09"

Thank you!

1 Answers1

1

You could do this by subtracting the same date, with the clock set to midnight:

const timeStamp = 1671682809;
const date = new Date(timeStamp * 1000);
const midnightDate = new Date(date).setHours(0,0,0,0);
const justHMS = date - midnightDate;
// you may want to divide this number how you wish if you're not working in milliseconds
console.log(justHMS); 
Ryan_DS
  • 750
  • 7
  • 28
  • This presumes the local time zone is applicable, and it also presumes that midnight exists on the day in question in the local time zone. Yes, there are days without midnight - when a time zone has a forward transition that skips from 00:00 to 01:00, such as start of DST in Cuba (and others). – Matt Johnson-Pint Dec 22 '22 at 06:18