Getting the time in JavaScript is pretty simple. Using the Date constructor will give us the time as set on the user’s computer, but what if we want the accurate time, or the time in a different timezone?
Even with getTimezoneOffset()
you’re still relying on the client!
It turns out that the only way of getting a complete and accurate time from any timezone requires a little bit of server interaction. Luckily there are a few APIs out there that offer this service (actually, there’s only one; well I couldn’t find any others)!
Here we’re using the ‘json-time’ API developed by Simon Willson:
JSON-time
function getTime(zone, success) { var url = 'http://json-time.appspot.com/time.json?tz=' + zone, ud = 'json' + (+new Date()); window[ud]= function(o){ success && success(new Date(o.datetime), o); }; document.getElementsByTagName('head')[0].appendChild((function(){ var s = document.createElement('script'); s.type = 'text/javascript'; s.src = url + '&callback=' + ud; return s; })()); } |
Usage
The first parameter of the callback function is the time (having been passed through the Date constructor), so you can use Date methods such as getSeconds()
etc. The second parameter is the entire object returned from the JSON request.
// Alert GMT: getTime('GMT', function(time){ alert(time); }); // Get London time, and format it: getTime('Europe/London', function(time){ var formatted = time.getHours() + ':' + time.getMinutes() + ':' + time.getSeconds(); alert( 'The time in London is ' + formatted ); }); |
For reference, here’s a list of all the available timezones (to use one, remove the backslash).
jQuery version
$.getTime = function(zone, success) { var url = 'http://json-time.appspot.com/time.json?tz=' + zone + '&callback=?'; $.getJSON(url, function(o){ success && success(new Date(o.datetime), o); }); }; // Usage: $.getTime('GMT', function(time){ alert(time); }); |
MooTools version
You’ll need to download the JsonP class.
function getTime(zone, success) { var url = 'http://json-time.appspot.com/time.json'; new JsonP(url, { data: { tz: zone }, onComplete: function(o){ success && success(new Date(o.datetime), o); } }).request(); } // Usage: getTime('GMT', function(time){ alert(time); }); |
Thank you Simon Willison for making this API; seriously, I searched around the entire internets just for one damn API and I almost lost hope!
Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!
Why not do a HTTP Head request to google.com to get the current time? I have used it in apps that need to check the correct time and never found different from ntp servers.
Peter
Peter, good idea, I hadn’t thought of that. I suppose that’s a better solution if you’re looking to get the time in the same timezone.