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.SyntaxdateObj.toDateString();JavaScriptconst date = new Date(); const formatDate = date.toDateString(); con
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 Cont
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 Conte
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 ContentUsing 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 ContentUsing new Date()Using Date.parse() Using Date.UTC()Using new Date()In this approac
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. html <!DOCTYPE
2 min read
How to Convert String to JSON in TypeScript ? Converting a string to JSON is essential for working with data received from APIs, storing complex data structures, and serializing objects for transmission. Below are the approaches to converting string to JSON in TypeScript:Table of ContentConvert String to JSON Using JSON.parse()Convert String to
5 min read
How to Calculate the Time Between 2 Dates in TypeScript ? In this article, we will calculate the time between two different dates using TypeScript. We will use the getTime() method to get the current time of the specified date. Syntax:const variable_name = new Date();const time = variable_name.getTime();Note: The getTime() method will return the time in th
2 min read
How to Validate String Date Format in JavaScript ? Validating string date format in JavaScript involves verifying if a given string conforms to a specific date format, such as YYYY-MM-DD or MM/DD/YYYY. This ensures the string represents a valid date before further processing or manipulation. There are many ways by which we can validate whether the D
5 min read