EN
TypeScript - custom date & time format
0 points
In this article, we would like to show you how to use the custom format date and time in TypeScript.
In this example, we will use the padStart
function, which pads the given string with another string until it is the desired length.
xxxxxxxxxx
1
const renderNumber = (value: number, size: number): string => {
2
const text = String(value);
3
return text.padStart(size, '0');
4
};
5
6
const formatDate = (date: Date = new Date()): string => {
7
const year = renderNumber(date.getFullYear(), 4);
8
const month = renderNumber(date.getMonth() + 1, 2);
9
const day = renderNumber(date.getDate(), 2);
10
const hours = renderNumber(date.getHours(), 2);
11
const minutes = renderNumber(date.getMinutes(), 2);
12
const seconds = renderNumber(date.getSeconds(), 2);
13
return `${year}.${month}.${day}_${hours}.${minutes}.${seconds}`;
14
};
15
16
17
// Usage example:
18
19
const date = new Date(2000, 5, 15, 12, 30, 20);
20
21
console.log(formatDate()); // 2022.03.11_15.05.12
22
console.log(formatDate(date)); // 2000.06.15_12.30.20
Output:
xxxxxxxxxx
1
2022.03.11_15.07.15
2
2000.06.15_12.30.20
Note:
The
padStart
function is a relatively new feature (ES2017) and may not be compatible with all browsers.