Many JavaScript applications require adding time zones and local time in the specific time zones. We can easily get the local time of our current location by using the Date()
method in JavaScript. However, it may be troublesome to get the local time of a specific time zone. The Date()
function returns the data as per a user’s current location. i.e. from where they run the application. Suppose you are using an application from Asia, Dubai and it should also show the current time in Europe, London. Let’s see how to define a function that will help us get the local time for a time zone in JavaScript.
changeTimeZone()
function
You may define a changeTimeZone()
as shown below.
function changeTimeZone(date, timeZone) {
if (typeof date === 'string') {
return new Date(
new Date(date).toLocaleString('en-US', {
timeZone,
}),
);
}
return new Date(
date.toLocaleString('en-US', {
timeZone,
}),
);
}
This takes in as parameters the date (the date details at your current location) and a preferred time zone. It then validates if the date entered is of type string, as we need all elements here, the day, month, year, time, etc. So later we can format date with these detail as per our choice.
You may call this function and pass the two parameters, your current date and the time zone to convert the date to. Let’s see what function best lists all time zones and helps you decide which one to chose.
Fetch International Time Zones
Getting all available time zones in the world and ones that your environment supports using a function is always beneficial rather than to hard code them yourself.
let arys = Intl.supportedValuesOf('timeZone');
The JavaScript function above lists all available time zone in the world. This returns an array of around 400+ different time zones. You can read your preferred time zone from this huge array and manipulate is as per your choice, or pass it to the changeTimeZone()
function.
Suppose you need the time for any time zone in America, you can use the code snippet below.
const zone = arys.find(ary => ary.includes('America/Los_Angeles') || ary.includes('America/Chicago') || ary.includes('America/New_York'));
console.log("zone america", zone);
This will read values from the array and return any one of the time zones of America as listed above. You can now pass this time zone and your current time to the changeTimeZone()
function and get the date and time details for the mentioned time zone of America.
const zone_date = changeTimeZone(date, zone);
console.log("zone time...",zone_date); //
var current_day_zone = days[zone_date.getDay()];
var current_month_zone = months[zone_date.getMonth()];
var full_time_zone = zone_date.toLocaleTimeString();
const current_time_zone = full_time_zone.replace(/:\d+ /, ' ');
The days and months arrays hold values of different days, that will help format your time and date returned. These arrays combined with different functions can help you format your date and time in different ways.