How to Format Dates in TypeScript

Formatting dates properly in TypeScript can be a crucial requirement, especially in applications that involve scheduling, logging, or displaying timelines.

For example, date values are in a standard format, such as ISO (2025-05-06T12:34:56Z), and need to be converted into a more readable or user-friendly format for reports, UI displays, or data processing.

In this tutorial, we will explore different methods for formatting dates in TypeScript, including built-in JavaScript functions and popular libraries like date-fns and Moment.js.

Understanding the Date Object in TypeScript

To format dates in TypeScript, it’s essential to understand the Date object. The Date object represents a single moment in time and allows you to work with dates and times in your TypeScript code. You can create a Date object using the new Date() constructor.

Here’s an example of creating a Date object representing the current date and time:

const currentDate = new Date();
console.log(currentDate); // Output: Current date and time

Formatting Dates using the toLocaleDateString Method

One of the simplest ways to format a date in TypeScript is by using the toLocaleDateString method. This method allows you to convert a Date object to a string representation based on the specified locale and formatting options.

Here’s an example of formatting a date using toLocaleDateString:

const today = new Date();
const formattedDate = today.toLocaleDateString('en-US', {
  year: 'numeric',
  month: 'long',
  day: 'numeric'
});
console.log(formattedDate); 

Output:

Format date for locale in Typescript

In this example, we create a Date object representing today’s date. We then use the toLocaleDateString method to format the date as “Month, Day, Year” according to the ‘en-US‘ locale.

Using External Libraries for Date Formatting

While the built-in methods provide basic date formatting capabilities, sometimes you may need more advanced formatting options. In such cases, you can leverage external libraries that offer a wide range of formatting functions.

One popular library for date formatting in TypeScript is date-fns. It provides a comprehensive set of functions to parse, manipulate, and format dates.

You first need to install the date-fns library with the command below:

npm install date-fns

Here’s an example of formatting a date using the format function from date-fns:

import {format} from 'date-fns';

const currentDate = new Date();
const formattedDate = format(currentDate, 'MM/dd/yyyy HH:mm');
console.log(formattedDate); 

Output:

Date format in typescript using fns

In this example, we import the format function from the date-fns library. We then use it to format the current date as “MM/dd/yyyy HH:mm”.

Defining Custom Date Formats

In some cases, you may need to define custom date formats to match specific requirements. TypeScript allows you to create custom type aliases to represent different date formats.

Here’s an example of defining custom date formats using type aliases:

type DateFormat = 'MM-dd-yyyy' | 'yyyy-MM-dd' | 'ISO 8601';

const formatDate = (date: Date, format: DateFormat): string => {
  const pad = (n: number) => n.toString().padStart(2, '0');
  const year = date.getFullYear();
  const month = pad(date.getMonth() + 1); 
  const day = pad(date.getDate());

  switch (format) {
    case 'MM-dd-yyyy':
      return `${month}-${day}-${year}`;
    case 'yyyy-MM-dd':
      return `${year}-${month}-${day}`;
    case 'ISO 8601':
      return date.toISOString();
    default:
      throw new Error('Unsupported date format: ${format}');
  }
};

const today = new Date();
const formattedDate = formatDate(today, 'ISO 8601');
console.log(formattedDate);

In this example, we define a type alias called DateFormat that represents three different date formats:

‘MM-dd-yyyy’ (05-06-2025), ‘yyyy-MM-dd’ (2025-05-06), ‘ISO 8601’ (2025-05-06T00:00:00.000Z).

It uses a helper to pad single-digit days/months with a zero and returns the formatted string based on the input format. The final lines create the current date and log it in ISO 8601 format.

We then use formatDate, a function that takes a Date object and a DateFormat as parameters and returns the formatted date as a string.

Output:

For MM-dd-yyyy format:

Format date to ISO format in typescript

For yyyy-MM-dd format:

Typescript format date in custom format

For ISO format:

Remove string from string python

Parsing and Validating Date Strings

When working with date strings received from external sources or user input, it’s crucial to parse and validate them to ensure they are in the expected format. TypeScript provides the Date.parse method to parse a date string and create a corresponding Date object.

Here’s an example of parsing and validating a date string:

const dateString = '2025-05-06';
const parsedDate = Date.parse(dateString);

if (!isNaN(parsedDate)) {
  const date = new Date(parsedDate);
  console.log(date); 
} else {
  console.log('Invalid date string');
}

Output:

Python read file into a list

In this, we have a date string in the format “yyyy-MM-dd”. We use the Date.parse method to parse the string and create a timestamp. If the parsing is successful (i.e., the timestamp is not NaN), we create a new Date object using the parsed timestamp. Otherwise, we log an error message indicating an invalid date string.

Conclusion

In this tutorial, we have learned how to work with and format dates in TypeScript using various methods. We performed date formatting using built-in methods like toLocaleDateString. We also used external libraries such as date-fns for more advanced formatting needs.

We also learned how to define and use custom date formats and parse and validate date strings. With these methods, you can effectively manage and display dates in a way that suits your application’s requirements.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.