How to use date-fns In Express

Date-fns is a modern JavaScript date utility library that provides a wide range of functions for manipulating and formatting dates. To use date-fns with TypeScript, first, install the library:

npm install date-fns

Example: Importing the format function from date-fns, creating a Date object for the current date, then formatting it as “dd MMM yyyy” (’01 May 2024′).

JavaScript
import { format } from 'date-fns';

const currentDate: Date = new Date();
const formattedDate: string = format(currentDate, 'dd MMM yyyy');
console.log(formattedDate);

Output:

01 May 2024

How to express a Date Type in TypeScript ?

In this tutorial, we will learn about expressing the date type in TypeScript. Generally, In JavaScript, the classes can be used to add types similarly in TypeScript the classes, type alias, and the interfaces can also be used to add types to the variables.

Some ways of expressing date type in TypeScript are listed below:

Table of Content

  • Without specifying any of the types
  • Manually Typing Date Object
  • Using type alias or interface for typing
  • Using date-fns

Similar Reads

Without specifying any of the types

In TypeScript, if we do not provide a Date type to the Date object, then it will type it using the internal inference as the Date object returns the date as a result. By default, the date object returns the current date if there is no parameter passed to it to get the particular date and time....

Manually Typing Date Object

We can also type the date object manually using the Date type. It is the same type that gets inferred automatically by TypeScript when we do not specify any type....

Using type alias or interface for typing

In this approach, we will first define an interface or an type alias with a property of Date type and then use those created types to type the actual date object we will create using the new Date()....

Using date-fns

Date-fns is a modern JavaScript date utility library that provides a wide range of functions for manipulating and formatting dates. To use date-fns with TypeScript, first, install the library:...