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.

JavaScript
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

Similar Reads

Using toLocaleString() method

TypeScript provides the built-in toLocaleString() method that allows us to format the default date based on the user’s locale. It includes information about the date, time, and region....

Using toLocaleDateString() method

The toLocaleDateString method allows us to customize the date format by specifying options such as the year, month and day. We mostly use this approach when we want to control individual date components according to the desired format....

Using Custom Formatting

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....

Using date-fns Library

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....

Contact Us