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.
We can use this function as shown below:
toLocaleString()
toLocaleString(locales)
toLocaleString(locales, options)
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 anden-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.
toLocaleString()
returns the number or date in the specified local format.
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}`)
In the following code snippet, we convert the date 2012-11-20T14:00:00.000Z
to US local format.
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 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 }));