EN
TypeScript - convert unix timestamp to time
0 points
In this article, we would like to show you how to convert unix timestamp to HH:mm:ss
time in TypeScript.
Quick solution:
xxxxxxxxxx
1
const getTime = (timestamp: number): string => {
2
const date = new Date(1000 * timestamp); // unix timestamp in seconds to milliseconds conversion
3
const time = date.toTimeString();
4
return time.substring(0, 8);
5
};
6
7
8
// Usage example:
9
10
const timestamp: number = 1630564245; // unix timestamp in seconds
11
12
console.log(getTime(timestamp)); // 08:30:45
Note:
In this example we multiply the timestamp by
1000
(to get milliseconds) and usetoTimeString()
to get the time string.
In this example, we handle the string conversion in our own way.
Practical example:
xxxxxxxxxx
1
const getString = (input: number): string => (input < 10 ? '0' + input : input.toString());
2
3
// Converts unix timestamp in seconds to HH:mm:ss string.
4
//
5
const getTime = (timestamp: number): string => {
6
const date = new Date(1000 * timestamp);
7
const hours = getString(date.getHours());
8
const minutes = getString(date.getMinutes());
9
const seconds = getString(date.getSeconds());
10
return `${hours}:${minutes}:${seconds}`;
11
};
12
13
14
// Usage example:
15
16
const timestamp = 1630564245; // unix timestamp in seconds
17
18
console.log(getTime(timestamp)); // 08:30:45
Output:
xxxxxxxxxx
1
08:30:45