Local Time script
Note (Nov 22nd, 16'): Script rewritten to use moment.js library for built in way to get time zone offsets.
Description: Want to display the current local time of a specific place in the world? This totally self contained JavaScript lets you do that for any place on Earth- enter the desired time zone string to display the time for (ie: "America/Toronto"), and the format of the date and time to output. It uses the moment.js library to retrieve the corresponding time zone offset, which accounts for Daylight Savings Time too to consistently display the correct target time.
Finally, this script can be called multiple times on the same page to display simultaneously the local times of different places. Cool!
Demo:
Step 1: Insert the below script into the HEAD section of your page:
The code references two external libraries, which you should download below:
Step 2:
Inside your <BODY>, define a DIV or SPAN tag with a unique ID that will
contain the local time, then invoke "showLocalTime()
" to populate it:
Here's an explanation of the 3 parameters of showLocalTime()
:
- ContainerID (string): The ID of the DIV or span that will house the local time.
- Time Zone Id (string): A valid time zone identifier string to specify the time zone of the target location you wish to display the time for, such as "Asia/Jakarta".
-
Time Format (string): The format of the final displayed date and time.
Pass in the desired "tokens" as described on Moment.js's
Date
Formatting Section, such as:
- "
ddd, hA
": Sun, 2AM - "
hh:mm:ss A (ddd)
": 02:22:54 AM (Sun) - "
dddd, MMMM Do YYYY, h:mm:ss a
": Sunday, November 19th 2016, 02:22:54 pm
- "
And that's it! Regardless of the final format you've chosen, the displayed time will be updated every second, live.