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.
This function returns a string containing formatting data for the current date/time, based on the provided locale string.
function getDateFormatString(locale) {
const options = {
hour: "numeric",
minute: "numeric",
second: "numeric",
day: "numeric",
month: "numeric",
year: "numeric",
};
const formatObj = new Intl.DateTimeFormat(locale, options).formatToParts(
Date.now()
);
return formatObj
.map((obj) => {
switch (obj.type) {
case "hour":
return "HH";
case "minute":
return "MM";
case "second":
return "SS";
case "day":
return "DD";
case "month":
return "MM";
case "year":
return "YYYY";
default:
return obj.value;
}
})
.join("");
}
console.log(getDateFormatString("en-US")); //Expected Output: "MM/DD/YYYY, HH:MM:SS PM"
console.log(getDateFormatString("ko-KR")); //Expected Output: "YYYY. MM. DD. 오후 HH:MM:SS"
Edit options to change the data extracted from the date object and edit/add cases to accommodate it.
Find the documentation for DateTimeFormat here.
I adapted the function from an article on newbedev.com.
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: ١٢:١٥:٣٠ص
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()