What is the toLocaleString() function in TypeScript?

Overview

TypeScript provides the toLocaleString() function that converts a number or date into locale format.

This function is useful when we want to display a number or date in the locale language format.

For example, if users are in English- and Arabic-speaking countries, we can display the date in the en-US or ar-EG format, respectively.

Syntax

We can use this function as shown below:

toLocaleString()
toLocaleString(locales)
toLocaleString(locales, options)

Parameters

From the above syntax, we can see that this function accepts locales and options as parameters.

  • locales: This is where we specify the language format into which we want to convert the date.

Some examples are en-US for US English and en-GB for British English.

  • options: This helps us customize the format returned from the toLocaleString() function.

Some examples are specifying the time zone, or choosing between the 12 or 24 hour format.

Return value

toLocaleString() returns the number or date in the specified local format.

Example 1

In the following code snippet, we convert the number 250000000 into US local format with the toLocaleString("en-us") function (where en-us is the locale parameter).

Click the run button below to display the outputs in both the original format and the updated formats.

var originalNum:number = 250000000
//formatting number
var formattedNum = originalNum.toLocaleString("en-US");
//printing the original and formatted numbers
console.log(`Original number is ${originalNum}`)
console.log(`Formatted Number is ${formattedNum}`)

Example 2

In the following code snippet, we convert the date 2012-11-20T14:00:00.000Z to US local format.

  • In the first line, we construct the date object.
  • In line 4, we print the original date to console.
  • In line 7, we convert the date into US format and printing it to the console.
  • Line 10 provides the timezone and hour12 as options to customize the date. Here we mentioned hour12 as false, then the time prints in 24 hrs format.

Run the following code snippet to display the converted date formats.

let date:Date = new Date(Date.UTC(2012, 11, 20, 14, 0, 0));
//prints original date
console.log(date)
//prints in United States english format
console.log(date.toLocaleString('en-us'));
//providing options
console.log(date.toLocaleString('en-us', { timeZone: 'UTC', hour12: false }));

Free Resources