EN
TypeScript - format current date to yyyy-mm-dd (Iso 8601)
0
points
In this article, we would like to show you how to format the current date to yyyy-mm-dd using TypeScript.
Quick solution:
// output format: yyyy-mm-dd
const getDateInFormat_yyyy_mm_dd = (): string => {
const toString = (date: number, padLength: number) => {
return date.toString().padStart(padLength, '0');
};
const date = new Date();
const dateTimeNow = toString(date.getFullYear(), 4) + '-' + toString(date.getMonth() + 1, 2) + '-' + toString(date.getHours(), 2);
return dateTimeNow;
};
console.log(getDateInFormat_yyyy_mm_dd()); // 2022-03-13
Output:
2022-03-13
Practical examples
Example 1
// output format: yyyy-mm-dd
const getDateInISO_8601 = (): string => {
const date = new Date();
const 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()); // 2022-03-14
Output:
2022-03-14
Example 2
const getIso8601Date = (date?: Date): string => {
if (date == null) {
date = new Date();
}
const year = String(date.getFullYear());
let month = String(date.getMonth() + 1);
let day = String(date.getDate());
if (month.length < 2) {
month = '0' + month;
}
if (day.length < 2) {
day = '0' + day;
}
return year + '-' + month + '-' + day;
};
// Usage example:
const date = new Date(2021, 5, 13); // 2021-05-13 - e.g. recived from server
console.log(getIso8601Date(date)); // 2021-06-13
console.log(getIso8601Date()); // 2022-03-14
Output:
2021-06-13
2022-03-14