How to use date-fns Library In Typescript
Date-fns is a lightweight JavaScript date utility library that provides a comprehensive set of functions for manipulating and formatting dates. You can use it to achieve custom date formatting in TypeScript projects.
Installation
First, install the date-fns library using npm:
npm install date-fns
Example: The example imports the format function from the date-fns library to format the current date (currentDate) as ‘dd/MM/yyyy HH:mm’ and logs it.
import { format } from 'date-fns';
const currentDate: Date = new Date();
const formattedDate: string = format(currentDate, 'dd/MM/yyyy HH:mm');
console.log(formattedDate); // Output: 01/05/2024 06:10
Output:
01/05/2024 06:10
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