Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
How to express a Date Type in TypeScript ?
Next article icon

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:

Table of Content

  • Using toLocaleString() method
  • Using toLocaleDateString() method
  • Using Custom Formatting
  • Using date-fns Library
  • Using Intl.DateTimeFormat

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
How to express a Date Type in TypeScript ?

H

himanshusharma11199
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • TypeScript

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 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 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 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
  • 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
  • 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 Content Convert String to JSON Using JSON.parse()Convert String
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences