How to use Custom Formatting In Typescript
We can also format the dates in TypeScript more manually using template literals. Here we can create our own custom date string literals by calling methods like getFullYear, getMonth, etc. This method provides us the full control over the format of the date.
Syntax
const date = new Date();
const dateFormat = `${date.getDay()}/${date.getMonth()}/${date.getFullYear()}`;
Example: The below code uses the custom formatting method to format the date in TypeScript.
function dateCustomFormatting(date: Date): string {
const padStart = (value: number): string =>
value.toString().padStart(2, '0');
return
`${padStart(date.getDate())}/
${padStart(date.getMonth() + 1)}/
${date.getFullYear()}
${padStart(date.getHours())}:
${padStart(date.getMinutes())}`;
}
const date = new Date();
const dateFormat = dateCustomFormatting(date);
console.log(dateFormat);
Output:
"23/02/2024 14:04"
How to Format Date in TypeScript ?
Formatting dates is important especially when displaying them to the users or working with date-related data. TypeScript provides various ways to achieve this.
Below are the methods to format the date data type in TypeScript:
Table of Content
- Using toLocaleString() method
- Using toLocaleDateString() method
- Using Custom Formatting
- Using date-fns Library
Contact Us