How to Format Date in TypeScript ?
Last Updated :
01 Aug, 2024
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"
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"
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
Similar Reads
How to Format a Date in JavaScript ?
Here are different ways to format the date in JavaScript. 1. Using the toDateString() MethodThe toDateString() method formats the date object into a human-readable format as Day Month Date Year. Syntax dateObj.toDateString();[GFGTABS] JavaScript const date = new Date(); const formatDate = date.toDat
2 min read
How to express a Date Type in TypeScript ?
In TypeScript, the Date object is used to handle dates and times. To express a Date type, declare a variable with the type annotation Date and assign it a date value. This allows for precise date manipulation and formatting in your TypeScript code. Ways to Express Date Type in TypeScriptTable of Con
3 min read
How to Format Date with Moment.js?
Formatting dates is essential for presenting date and time information in a way that's readable and useful for users. Moment.js provides several methods for formatting dates from simple and predefined formats to more complex and localized representations. Below are different approaches: Table of Con
2 min read
How to Format date using strftime() in Python ?
In this article, we will see how to format date using strftime() in Python. localtime() and gmtime() returns a tuple representing a time and this tuple is converted into a string as specified by the format argument using python time method strftime(). Syntax: time.strftime(format[, sec]) sec: This i
2 min read
How to Declare Variables in TypeScript ?
In TypeScript, a variable can be defined by specifying the data type of the value it is going to store. It will store the values of the specified data type only and throws an error if you try to store the value of any other data type. You can use the colon syntax(:) to declare a typed variable in Ty
2 min read
How to Compare Two Date Strings in TypeScript ?
In TypeScript, we can compare two date strings by converting them to comparable formats using Date objects or by parsing them into the timestamps. We will discuss different approaches with the practical implementation of each one of them. Table of Content Using Date ObjectsUsing Date.parseUsing Intl
4 min read
How to Change input type="date" Format in HTML ?
The <input> element with type="date" is used to allow the user to choose a date. By default, the date format displayed in the input field is determined by the user's browser and operating system settings. However, it is possible to change the format of the date displayed in the input field usi
4 min read
How to Convert String to Date in TypeScript ?
In TypeScript, conversion from string to date can be done using the Date object and its method. We can use various inbuilt methods of Date object like new Date() constructor, Date.parse(), and Date.UTC. Table of Content Using new Date()Using Date.parse() Using Date.UTC()Using new Date()In this appro
2 min read
How to call Typescript function from JavaScript ?
In this article, we will try to understand all the facts which are associated with how we may call typescript function from JavaScript. TypeScript supports the existing JavaScript function syntax for declaring and calling it within the program or the code snippet. Let us quickly understand how we ma
2 min read
JavaScript | Date Formats
JavaScript Date Input: There are many ways in which one can format the date in JavaScript. Formats: ISO Date "2019-03-06" (The International Standard) Short Date "03/06/2019" Long Date "Mar 06 2019" or "06 Mar 2019" Example 1: This example uses ISO date format to display the date. <!DOCTYPE html
2 min read