Home > front end >  Get the format of time for any country
Get the format of time for any country

Time:11-18

There is a way to get the time format based on timezone in JS? what I want is something like that: getSpecificTimeFormat("America/New_York") returns "h:mm a" and getSpecificTimeFormat("Europe/Paris") returns "HH:mm" and so on.

CodePudding user response:

At mozilla.org there are clear instructions on how to do this using the .toLocaleTimeString() function.

Examples taken directly from the website:

You can find the documentation here

// Depending on timezone, your results will vary
const event = new Date('August 19, 1975 23:15:30 GMT 00:00');

console.log(event.toLocaleTimeString('en-US'));
// expected output: 1:15:30 AM

console.log(event.toLocaleTimeString('it-IT'));
// expected output: 01:15:30

console.log(event.toLocaleTimeString('ar-EG'));
// expected output: ١٢:١٥:٣٠ص
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Get time zone

- new Date().getTimezoneOffset() / 60

Obtain the time based on the time zone

const num=- new Date().getTimezoneOffset() / 60;

const newDate=new Date(new Date().getTime() num*60*60*1000).toISOString()
  • Related