EN
TypeScript - convert unix timestamp to human readable
0 points
In this article, we would like to show you how to convert unix timestamp to human readable in TypeScript.
Quick solution:
xxxxxxxxxx
1
const timestamp: number = 1630564245; // unix timestamp in seconds
2
const date: Date = new Date(timestamp * 1000);
3
4
console.log(date); // 2021-09-02T06:30:45.000Z
In this example, we display unix timestamp in human readable form by converting it to the Date
object.
xxxxxxxxxx
1
const timestamp: number = 1630564245; // unix timestamp in seconds
2
const date: Date = new Date(timestamp * 1000);
3
4
console.log(date); // 2021-09-02T06:30:45.000Z
Output:
xxxxxxxxxx
1
Thu Sep 02 2021 08:30:45 GMT+0200 (Central European Summer Time)
2
2021-09-02T06:30:45.000Z
In this example, we display unix timestamp in human readable form by converting it to the time string.
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
const parts = time.split(' ');
5
return parts[0];
6
};
7
8
9
// Usage example:
10
11
const timestamp: number = 1630564245; // unix timestamp in seconds
12
console.log(getTime(timestamp)); // 08:30:45
Output:
xxxxxxxxxx
1
08:30:45