EN
TypeScript - format current Date to yyyy-mm-dd hh-mm-ss-SSS
0 points
In this article, we would like to show you how to format the current Date to yyyy-mm-dd hh-mm-ss-SSS in TypeScript.
Quick solution:
xxxxxxxxxx
1
const format = (input: number, padLength: number): string => {
2
return input.toString().padStart(padLength, '0');
3
};
4
5
const date = new Date();
6
7
const dateTimeNow =
8
format(date.getFullYear(), 4) +
9
'_' +
10
format(date.getMonth() + 1, 2) +
11
'_' +
12
format(date.getDate(), 2) +
13
'__' +
14
format(date.getHours(), 2) +
15
'_' +
16
format(date.getMinutes(), 2) +
17
'_' +
18
format(date.getSeconds(), 2) +
19
'_' +
20
format(date.getMilliseconds(), 3);
21
22
// 2022_03_14__14_20_29_865
23
console.log(dateTimeNow);
Example output:
xxxxxxxxxx
1
2022_03_14__14_20_29_865
The same code wrapped in the method for quick copy / paste:
xxxxxxxxxx
1
const getDateInFormat_yyyy_mm_dd_hh_mm_ss_SSS = () => {
2
const toString = (number, padLength) => {
3
return number.toString().padStart(padLength, '0');
4
};
5
6
const date = new Date();
7
8
const dateTimeNow =
9
toString(date.getFullYear(), 4) +
10
'_' +
11
toString(date.getMonth() + 1, 2) +
12
'_' +
13
toString(date.getDate(), 2) +
14
'__' +
15
toString(date.getHours(), 2) +
16
'_' +
17
toString(date.getMinutes(), 2) +
18
'_' +
19
toString(date.getSeconds(), 2) +
20
'_' +
21
toString(date.getMilliseconds(), 3);
22
return dateTimeNow;
23
};
24
25
// 2022_03_14__14_21_48_983
26
console.log(getDateInFormat_yyyy_mm_dd_hh_mm_ss_SSS());
Example output:
xxxxxxxxxx
1
2022_03_14__14_21_48_983