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:
// ONLINE-RUNNER:browser;
// output format: yyyy-mm-dd
function getDateInFormat_yyyy_mm_dd() {
function toString(text, padLength) {
return text.toString().padStart(padLength, '0');
}
let date = new Date();
let dateTimeNow =
toString( date.getFullYear(), 4 )
+ '-' + toString( date.getMonth() + 1, 2 )
+ '-' + toString( date.getHours(), 2 )
;
return dateTimeNow;
}
console.log(getDateInFormat_yyyy_mm_dd()); // 2021-05-13
Output:
2021-05-13
Next example
// ONLINE-RUNNER:browser;
// output format: yyyy-mm-dd
function getDateInISO_8601() {
let date = new Date();
let year = '' + date.getFullYear();
let month = '' + (date.getMonth() + 1);
let day = '' + date.getDate();
if (month.length < 2) {
month = '0' + month;
}
if (day.length < 2) {
day = '0' + day;
}
return year + '-' + month + '-' + day;
}
console.log(getDateInISO_8601()); // 2021-05-13
Output:
2021-05-13
Next example
// ONLINE-RUNNER:browser;
// output format: yyyy-mm-dd
//
function getIso8601Date(date) {
if (date == null) {
date = new Date();
}
var year = String(date.getFullYear());
var month = String(date.getMonth() + 1);
var day = String(date.getDate());
if (month.length < 2) {
month = '0' + month;
}
if (day.length < 2) {
day = '0' + day;
}
return year + '-' + month + '-' + day;
}
// Usage example:
var now = new Date(2021, 05, 13); // 2021-05-13 - e.g. recived from server
console.log(getIso8601Date(now)); // 2021-05-13
console.log(getIso8601Date()); // 2021-05-13