Open In App

How to Format Date in TypeScript ?

Last Updated : 01 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

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.

Syntax

const date = new Date();
const formattedDate = date.toLocaleString();

Example: The below code uses the toLocaleString() method to format the date in TypeScript.

JavaScript
const date = new Date();
const formattedDate:string = date.toLocaleString();
console.log(formattedDate);

Output:

"2/23/2024, 2:02:29 PM" 

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.

Syntax

const date = new Date();
const formattedDate = date.toLocaleDateString()

Example: The below code uses the toLocaleDateString() method to format the date in TypeScript.

JavaScript
const date = new Date();
const options: Intl.DateTimeFormatOptions = {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
};
const formattedDate: string = date.toLocaleDateString(undefined, options);
console.log(formattedDate);


Output:

"February 23, 2024" 

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.

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.

JavaScript
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" 

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.

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

Using Moment.js Library

This approach is particularly useful when you need to format dates in specific string patterns that aren't directly supported by native JavaScript date methods. Moment.js also handles time zones and locale-specific formatting, which can be very handy for international applications.

Installation To use Moment.js in a TypeScript project, you first need to install it using npm:

npm install moment

Example Here's how you can use Moment.js to format dates:

JavaScript
import moment from 'moment';

const date = new Moment();
const formattedDate = date.format('MMMM DD, YYYY HH:mm:ss');
console.log(formattedDate);

Output:

"June 19, 2024 15:45:30"

Using Intl.DateTimeFormat

The Intl.DateTimeFormat object is a built-in JavaScript object that provides a way to format dates and times based on the locale and formatting options. This approach is highly customizable and supports various locales, making it a powerful tool for formatting dates in TypeScript.

Example: The following code demonstrates how to use the Intl.DateTimeFormat object to format a date in TypeScript.

JavaScript
// Define the date to format
const date = new Date('2024-02-23T14:04:00');
const locale = 'en-US';
const options: Intl.DateTimeFormatOptions = {
  weekday: 'long',
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit'
};
const formatter = new Intl.DateTimeFormat(locale, options);
const formattedDate = formatter.format(date);
console.log(formattedDate);

Output:

Friday, February 23, 2024, 02:04:00 PM

Next Article

Similar Reads