EN
TypeScript - custom date & time format
0
points
In this article, we would like to show you how to use the custom format date and time in TypeScript.
Practical example
In this example, we will use the padStart function, which pads the given string with another string until it is the desired length.
const renderNumber = (value: number, size: number): string => {
const text = String(value);
return text.padStart(size, '0');
};
const formatDate = (date: Date = new Date()): string => {
const year = renderNumber(date.getFullYear(), 4);
const month = renderNumber(date.getMonth() + 1, 2);
const day = renderNumber(date.getDate(), 2);
const hours = renderNumber(date.getHours(), 2);
const minutes = renderNumber(date.getMinutes(), 2);
const seconds = renderNumber(date.getSeconds(), 2);
return `${year}.${month}.${day}_${hours}.${minutes}.${seconds}`;
};
// Usage example:
const date = new Date(2000, 5, 15, 12, 30, 20);
console.log(formatDate()); // 2022.03.11_15.05.12
console.log(formatDate(date)); // 2000.06.15_12.30.20
Output:
2022.03.11_15.07.15
2000.06.15_12.30.20
Note:
The
padStartfunction is a relatively new feature (ES2017) and may not be compatible with all browsers.