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-USfor US English anden-GBfor British English.
options: This helps us customize the format returned from thetoLocaleString()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 numbervar formattedNum = originalNum.toLocaleString("en-US");//printing the original and formatted numbersconsole.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
timezoneandhour12as options to customize the date. Here we mentionedhour12asfalse, then the time prints in24 hrsformat.
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 dateconsole.log(date)//prints in United States english formatconsole.log(date.toLocaleString('en-us'));//providing optionsconsole.log(date.toLocaleString('en-us', { timeZone: 'UTC', hour12: false }));