EN
JavaScript - format current Date to yyyy-mm-dd hh-mm-ss-SSS
2 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 JavaScript.
Quick solution:
xxxxxxxxxx
1
function toString(number, padLength) {
2
return number.toString().padStart(padLength, '0');
3
}
4
5
let date = new Date();
6
7
let dateTimeNow =
8
toString( date.getFullYear(), 4 )
9
+ '_' + toString( date.getMonth() + 1, 2 )
10
+ '_' + toString( date.getDate(), 2 )
11
+ '__' + toString( date.getHours(), 2 )
12
+ '_' + toString( date.getMinutes(), 2 )
13
+ '_' + toString( date.getSeconds(), 2 )
14
+ '_' + toString( date.getMilliseconds(), 3 )
15
;
16
17
// 2021_05_23__19_15_02_864
18
console.log(dateTimeNow);
Example output:
xxxxxxxxxx
1
2021_05_23__19_15_02_864
The same code wrapped in the method for quick copy / paste:
xxxxxxxxxx
1
function getDateInFormat_yyyy_mm_dd_hh_mm_ss_SSS() {
2
3
function toString(number, padLength) {
4
return number.toString().padStart(padLength, '0');
5
}
6
7
let date = new Date();
8
9
let dateTimeNow =
10
toString( date.getFullYear(), 4 )
11
+ '_' + toString( date.getMonth() + 1, 2 )
12
+ '_' + toString( date.getDate(), 2 )
13
+ '__' + toString( date.getHours(), 2 )
14
+ '_' + toString( date.getMinutes(), 2 )
15
+ '_' + toString( date.getSeconds(), 2 )
16
+ '_' + toString( date.getMilliseconds(), 3 )
17
;
18
19
return dateTimeNow;
20
}
21
22
console.log(getDateInFormat_yyyy_mm_dd_hh_mm_ss_SSS());