Date class provides a method called toLocaleString()
. Using the toLocaleString()
method, you can convert local time to EST (Eastern Standard Time).
The toLocaleString() method accepts two parameters:
1. locales: It is used to specify the language whose date formatting convention you want to use. You pass BCP 47 language tag to the locales parameter. For example, en-US for America, fr-FR for France, en-GB for the United Kingdom, etc.
Suppose you have passed en-US to the locales parameter, then the date is shown in month-date-year order, and time in 12-hour with AM/PM.
On the other hand, if you have passed en-GB, then the date is shown in the date-month-year order, and the time in 24-hour without AM/PM.
2. options: It is optional, and you pass an object to the options parameter. You specify various properties that control date and time formatting inside the object. One of the most important properties that you can pass to the options parameter is timeZone
. Using the timeZone property, you can convert local time to any time zone. It accepts time zone names of the IANA time zone database, such as "America/New_York", "Europe/London".
You can find a list of time zone databases on this page.
The following JavaScript code converts local time to EST (Eastern Standard Time):
let d = new Date(); console.log(d); //Fri Apr 08 2022 04:01:06 GMT+0530 (India Standard Time) console.log(d.toLocaleString('en-US', { timeZone: 'America/New_York', })); //4/7/2022, 6:31:06 PM
You can also format the date and time by specifying different properties to the options parameter.
The commonly used properties accepted by the options parameter are:
Properties | Value |
---|---|
year | 'numeric' e.g., 2022 '2-digit' e.g., 22 |
month | 'numeric' e.g., 4 '2-digit' e.g., 04 'long' e.g., April 'short' e.g., Apr |
day | 'numeric' e.g., 9 '2-digit' e.g., 09 |
hour | 'numeric' e.g., 6 '2-digit' e.g., 06 |
minute | 'numeric' e.g., 3 '2-digit' e.g., 03 |
second | 'numeric' e.g., 5 '2-digit' e.g., 05 |
dateStyle | 'full', 'long', 'medium' and 'short' |
timeStyle | 'full', 'long', 'medium' and 'short' |
If you want a complete list of properties that you can pass to the options parameter then visit this page.
The following example shows the day and month as 2-digits and year as 4-digit:
let d = new Date(); console.log(d.toLocaleString('en-US', { timeZone: 'America/New_York', year: 'numeric', month: '2-digit', day: '2-digit' })); //04/08/2022
If you want a detailed representation of the date and time then set the dateStyle
and timeStyle
properties to full
.
let d = new Date(); console.log(d.toLocaleString('en-US', { timeZone: 'America/New_York', dateStyle: 'full', timeStyle: 'full' })); //Friday, April 8, 2022 at 8:45:34 PM Eastern Daylight Time