How To Format Date/Time In TypeScript

How to format date/time in typescript

This article helps you format date/time in TypeScript. You can define reusable functions or use built-in functions provided by TypeScript. Let’s see what those ways are.

Format date/time in TypeScript

Method 1 – Use the built-in methods

There are many built-in methods provided by TypeScript. I will give an example of some commonly used functions:

let date = new Date(); 


9/22/2022, 11:14:16 AM
11:14:16 AM

In this example:

  • Date.getDate():  returns the day’s value. The value range is from 1 to 31.
  • Date.getMonth(): returns the month’s value. The value range is from 0 to 11.
  • Date.getFullYear(): returns the year’s value. The value range is from 1000 to 9999.
  • Date.toLocaleString(): returns a Date object as a String
  • Date.toLocaleDateString(): returns the date value of a Date object as a String.
  • Date.toLocaleTimeString(): returns the time value of a Date object as a String.

With just one command, you can easily get information about the day, month, year,… of a Date() object. However, the output will always be in a specific format and cannot be changed. This is also a limitation of this method.

Let’s look at the results. I intentionally used the getMonth method in the example. This method returns an integer from 0-11, with the value 0 representing January and 1 representing February, and so on. Therefore, if you want to get the exact value from 1-12 to represent 12 months of the year, we have to add 1 to the result.

Method 2 – Define reusable functions

This approach is based on the built-in methods mentioned above. However, with creating a reusable function, you can customize the output according to specific requirements. This is also a way to overcome the limitations of built-in functions.

See the example below. I define a function to return the result with the format YYYYMMDD

const date = new Date("2022-07-14");
function customFunc(date = new Date()){
    const y = String(date.getFullYear())
    const m = String(date.getMonth() + 1).padStart(2, '0')
    const d = String(date.getDate()).padStart(2, '0')
    return  "Format date: " + y + m + d


Format date: 20220922
Format date: 20220714

As you can see, we still use the built-in functions but add some changes to get the desired result. Specifically, in the above example, I have used the padStart() method to display the month and day in the correct MMDD format.  

You can customize it to get the results you want. Wrapping it all up in a function for reuse also makes your code easier to read and understand.


I have provided two ways to help you format date/time in TypeScript. Thank you for your interest in the content of the article.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *