Start a personal dev blog on your domain for free with Hashnode and grow your readership.
How to get the local time of a particular timezone in JavaScript?
I want to get the local / current time of a particular timezone, like I have a dropdown of all the GMT timezones(GMT), so on choosing a particular GMT I need to display its local / current time.
Atul Sharma
Full Stack Developer | Cloud Native Applications
Aug 31, 2017
function calcTime(city, offset) { d = new Date(); utc = d.getTime() + (d.getTimezoneOffset() * 60000); nd = new Date(utc + (3600000*offset)); return "The local time in " + city + " is " + nd.toLocaleString(); } // get Bombay time console.log(calcTime('Bombay', '+5.5')); // get Singapore time console.log(calcTime('Singapore', '+8')); // get London time console.log(calcTime('London', '+1'));
Just change the offset to that city and it will calculate current time for that timezone.
ajay ramgounda
Aug 31, 2017
ok, Thank you :)
Shehroz Saleem
Mar 26, 2022
this does not work on firefox
Peter Scheler
JS enthusiast
Aug 31, 2017
You can use
date.toLocaleTimeString(locale, options)
.There is a
timeZone
property in the options object. If you use it, thelocale
string only defines the format of the output.See here.
Tyler Dover
Aug 31, 2017
I'm still pretty new so, this may sound stupid but....
I was thinking you set a middle point in GMT as a var inside a function. GMT would be the time at GMT +0 and do a Switch statement. (Not using actual formatting or punctuation) Case time zone a; Answer = GMT -1 ; Break; Case time zone b; Answer = GMT +1; Break
Peter Scheler
Aug 31, 2017
ajay ramgounda You could use a map to replace the GMT Offset with a zone, but zones respect summer time and GMT Offsets not. So it is a bad solution:
const date = new Date() const map = new Map([ [-11, 'Pacific/Niue'], [-10, 'Pacific/Tahiti'], [-9, 'Pacific/Gambier'], [-8, 'Pacific/Pitcairn'], [-7, 'America/Vancouver'], [-6, 'America/Denver'], [-5, 'America/Rio_Branco'], [-4, 'America/Manaus'], [-3, 'America/Cayenne'], [-2, 'Atlantic/South_Georgia'], [-1, 'Atlantic/Azores'], [0, 'GMT'], [1, 'Europe/Brussels'], [2, 'Europe/Helsinki'], [3, 'Asia/Riyadh'], [4, 'Asia/Dubai'], [5, 'Asia/Tashkent'], [6, 'Asia/Urumqi'], [7, 'Asia/Bangkok'], [8, 'Asia/Singapore'], [9, 'Asia/Chita'], [10, 'Pacific/Chuuk'], [11, 'Pacific/Pohnpei'], [12, 'Pacific/Wake'], ]) date.toLocaleTimeString('en-US', {timeZone: map.get(-6)})
A better solution is a self made converter:
function dateToGMT(date = new Date(), offset = 0) { let hours = date.getUTCHours() + offset if (hours > 23) hours = 24 - hours if (hours < 0) hours = 24 + hours return `${hours}:${date.getUTCMinutes()}:${date.getUTCSeconds()}` }
Or you use something like moment.
Mike Classic
PHP, Android, JS
Aug 31, 2017
This doesn't directly answer your question because it's actually a library, but check out Moment JS Timezone.