EN
JavaScript - format current date to yyyy-mm-dd (Iso 8601)
5 points
In this article, we would like to show you how to format the current date to yyyy-mm-dd using JavaScript.

Quick solution:
xxxxxxxxxx
1
// output format: yyyy-mm-dd
2
function getDateInFormat_yyyy_mm_dd() {
3
4
function toString(text, padLength) {
5
return text.toString().padStart(padLength, '0');
6
}
7
8
let date = new Date();
9
10
let dateTimeNow =
11
toString( date.getFullYear(), 4 )
12
+ '-' + toString( date.getMonth() + 1, 2 )
13
+ '-' + toString( date.getHours(), 2 )
14
;
15
16
return dateTimeNow;
17
}
18
19
console.log(getDateInFormat_yyyy_mm_dd()); // 2021-05-13
Output:
xxxxxxxxxx
1
2021-05-13
xxxxxxxxxx
1
// output format: yyyy-mm-dd
2
function getDateInISO_8601() {
3
let date = new Date();
4
let year = '' + date.getFullYear();
5
let month = '' + (date.getMonth() + 1);
6
let day = '' + date.getDate();
7
8
if (month.length < 2) {
9
month = '0' + month;
10
}
11
if (day.length < 2) {
12
day = '0' + day;
13
}
14
return year + '-' + month + '-' + day;
15
}
16
17
console.log(getDateInISO_8601()); // 2021-05-13
Output:
xxxxxxxxxx
1
2021-05-13
xxxxxxxxxx
1
// output format: yyyy-mm-dd
2
//
3
function getIso8601Date(date) {
4
if (date == null) {
5
date = new Date();
6
}
7
8
var year = String(date.getFullYear());
9
var month = String(date.getMonth() + 1);
10
var day = String(date.getDate());
11
12
if (month.length < 2) {
13
month = '0' + month;
14
}
15
if (day.length < 2) {
16
day = '0' + day;
17
}
18
19
return year + '-' + month + '-' + day;
20
}
21
22
// Usage example:
23
24
var now = new Date(2021, 05, 13); // 2021-05-13 - e.g. recived from server
25
26
console.log(getIso8601Date(now)); // 2021-05-13
27
console.log(getIso8601Date()); // 2021-05-13