Nanfeng

Notes on software development, code, and curious ideas

Formatting a Timestamp in TypeScript

I needed to display a timestamp alongside a player’s match history in this format:

2023-11-29 10:08:04

The server returned the value as 2023-11-29T10:08:04.33+08:00, so I formatted it with the following TypeScript code:

1
2
3
4
5
6
7
8
9
10
11
12
const timestamp = "2023-11-29T10:08:04.33+08:00";
const date = new Date(timestamp);

const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
const seconds = date.getSeconds().toString().padStart(2, '0');

const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
console.log(formattedDate);

new Date(timestamp) reads the offset in the ISO timestamp, while the local getter methods format the result in the runtime’s local time zone. If the output must always use a specific time zone regardless of the user’s device, use Intl.DateTimeFormat with an explicit timeZone option or format it on the server.

+