[ACCEPTED]-Getting the current GMT world time-javascript

Accepted answer
Score: 27

You can use JSON[P] and access a time API:

(The 2 code below should work perfectly, just tested 1 it...)

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));
    };
    document.getElementsByTagName('head')[0].appendChild((function(){
        var s = document.createElement('script');
        s.type = 'text/javascript';
        s.src = url + '&callback=' + ud;
        return s;
    })());
}

getTime('GMT', function(time){
    // This is where you do whatever you want with the time:
    alert(time);
});
Score: 21

First, to get the accurate GMT time you 62 need a source that you trust. This means 61 some server somewhere. Javascript can generally 60 only make HTTP calls, and only to the server 59 hosting the page in question (same origin 58 policy). Thus that server has to be your 57 source for GMT time.

I would configure your 56 webserver to use NTP to synchronize its 55 clock with GMT, and have the webserver tell 54 the script what time it is, by writing a 53 variable to the page. Or else make and 52 XmlHttpRequest back to the server when you 51 need to know the time. The downside is 50 that this will be inaccurate due to the 49 latency involved: the server determines 48 the time, writes it to the response, the 47 response travels over the network, and the 46 javascript executes whenever the client's 45 cpu gives it a timeslice, etc. On a slow 44 link you can expect seconds of delay if 43 the page is big. You might be able to save 42 some time by determining how far off from 41 GMT the user's clock is, and just adjusting 40 all the time calculations by that offset. Of 39 course if the user's clock is slow or fast 38 (not just late or early) or if the user 37 changes the time on their PC then your offset 36 is blown.

Also keep in mind that the client 35 can change the data so don't trust any timestamps 34 they send you.

Edit: JimmyP's answer is very simple and easy 33 to use: use Javascript to add a <script> element 32 which calls a url such as http://json-time.appspot.com/time.json?tz=GMT. This is easier 31 than doing this yourself because the json-time.appspot.com 30 server works as a source of GMT time, and 29 provides this data in a way that lets you 28 work around the same-origin policy. I would 27 recommend that for simple sites. However 26 it has one major drawback: the json-time.appspot.com 25 site can execute arbitrary code on your 24 user's pages. This means that if the operators 23 of that site want to profile your users, or 22 hijack their data, they can do that trivially. Even 21 if you trust the operators you need to also 20 trust that they have not been hacked or 19 compromised. For a business site or any 18 site with high reliability concerns I'd 17 recommend hosting the time solution yourself.

Edit 2: JimmyP's answer has 16 a comment which suggests that the json-time 15 app has some limitations in terms of the 14 number of requests it can support. This 13 means if you need reliability you should 12 host the time server yourself. However, it 11 should be easy enough to add a page on your 10 server which responds with the same format 9 of data. Basically your server takes a 8 query such as

http://json-time.appspot.com/time.json?tz=America/Chicago&callback=foo

and returns a string such as

foo({
 "tz": "America\/Chicago", 
 "hour": 15, 
 "datetime": "Thu, 09 Apr 2009 15:07:01 -0500", 
 "second": 1, 
 "error": false, 
 "minute": 7
})

Note 7 the foo() which wraps the JSON object; this corresponds 6 to the callback=foo in the query. This 5 means when the script is loaded into the 4 page it will call your foo function, which 3 can do whatever it wants with the time. Server-side 2 programming for this example is a separate 1 question.

Score: 6

Why don't you send the time with every page? For 7 example somewhere in the html:

<span id="time" style="display:none;">
    2009-03-03T23:32:12
</span>

Then you could 6 run a Javascript while the site loads and 5 interpret the date. This would reduce the 4 amount of work the network has to do. You 3 can store the corresponding local time and 2 calculate the offset every time you need 1 it.

Score: 3

You could use getTimezoneOffset to get the offset between 11 the local date and the GMT one, and then 10 do the math. But this will only be as accurate 9 as the user's clock.

If you want an accurate 8 time, you should connect to a NTP server. Because 7 of the Same Origin Policy, you can't make a request with JS 6 to another server then yours. I'd suggest 5 you to create a server-side script that 4 connects to the NTP server (in PHP, or whatever 3 language you want) and return the accurate 2 date. Then, use an AJAX request to read 1 this time.

Score: 3

A little addition to Mr. Shiny and New and James answers

Here is 2 a PHP script which you can place on own 1 server and use instead of json-time.appspot.com

<?php
header('Content-Type: application/json');
header("Expires: Tue, 01 Jan 1990 00:00:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

$error = "false";
$tz = $_GET['tz'];

if ( !in_array($tz, DateTimeZone::listIdentifiers())) {
   $error = 'invalid time zone';
   $tz = 'UTC';
}

date_default_timezone_set($tz);

?>
<?php echo htmlspecialchars($_GET['callback'], ENT_QUOTES, 'UTF-8' ); ?>({
 "tz": "<?php echo $tz ?>",
 "hour": <?php echo date('G'); ?>,
 "datetime": "<?php echo date(DATE_RFC2822); ?>",
 "second": <?php echo intval(date('s')); ?>,
 "error": "<?php echo $error; ?>",
 "minute": <?php echo intval(date('i')); ?>
})
Score: 2

Like Mr. Shiny and New said, you need a server somewhere 39 with correct time. It can be the server 38 where you site are or some other server 37 that sends the correct time in a format 36 that you can read.

If you want to use the 35 date several times on your page, one or 34 more seconds apart, you probably don't want 33 to get the time from the server every time, but 32 instead cache the difference and use the 31 clients clock. If that is the case, here 30 is one of many solutions:

var MyDate = new function() {
    this.offset = 0;
    this.calibrate = function (UTC_msec) {
        //Ignore if not a finite number
        if (!isFinite(UTC_msec)) return;

        // Calculate the difference between client and provided time
        this.offset = UTC_msec - new Date().valueOf();

        //If the difference is less than 60 sec, use the clients clock as is.
        if (Math.abs(this.offset) < 60000) this.offset = 0;
    }
    this.now = function () {
        var time = new Date();
        time.setTime(this.offset + time.getTime());
        return time;
    }
}();

Include it on your 29 page and let your server side script produce 28 a row like:

MyDate.calibrate(1233189138181);

where the number is the current 27 time in milliseconds since 1 Jan 1970. You 26 can also use your favorite framework for 25 AJAX and have it call the function above. Or 24 you can use the solution JimmyP suggested. I have 23 rewritten JimmyPs solution to be included 22 in my solution. Just copy and paste the 21 following inside the function above:

    this.calibrate_json = function (data) {
        if (typeof data === "object") {
            this.calibrate (new Date(data.datetime).valueOf() );
        } else {
            var script = document.createElement("script");
            script.type="text/javascript";
            script.src=(data||"http://json-time.appspot.com/time.json?tz=UTC") +
                "&callback=MyDate.calibrate_json";
            document.getElementsByTagName('head')[0].appendChild(script);
        }
    }
    this.calibrate_json(); //request calibration with json

Notice 20 that if you change the name of the function 19 from MyDate you have to update the callback in 18 this.calibrate_json on the line script.src.

Explanation:

Mydate.offset is the current 17 offset between the server time and the clients 16 clock in milliseconds.

Mydate.calibrate( x ); is a function that 15 sets a new offset. It expects the input 14 to be the current time in milliseconds since 13 1 Jan 1970. If the difference between the 12 server and client clock is less than 60 11 seconds, the clients clock will be used.

Mydate.now() is 10 a function that returns a date object that 9 has the current calibrated time.

Mydate.calibrate_json( data ) is a function 8 that either takes an url to a resource that 7 gives back a datetime reply, or an object 6 with the current time (used as a callback). If 5 nothing is supplied, it will use a default 4 url to get the time. The url must have a 3 question mark "?" in it.

Simple 2 example of how to update an element with 1 the current time every second:

setInterval(
    function () {
        var element = document.getElementById("time");
        if (!element) return;
        function lz(v) {
            return v < 10 ? "0" + v : v;
        }
        var time = MyDate.now();
        element.innerHTML = time.getFullYear() + "-" +
            lz(time.getMonth() + 1) + "-" +
            lz(time.getDate()) + " " +
            lz(time.getHours()) + ":" +
            lz(time.getMinutes()) + ":" +
            lz(time.getSeconds())
        ;
},1000);
Score: 2

I stumbled upon another solution for those 7 who do not have access to the server side 6 of things. An answer to the question Getting the default server time in jQuery?.

Basically, you 5 can grab the "Date" header by 4 doing an AJAX HEAD request to "/". Not 3 all servers support this and it may take 2 some jiggery-pockery to get it working with 1 a particular server.

Check out the real answer for more details.

Score: 1

IMO, simplest solution is spinning up an 4 AWS Lambda (or Google Serverless) and attaching 3 it via API Gateway, giving you a timeserver 2 without managing any infrastructure. My 1 Lambda code:

import datetime
import json

def lambda_handler(event, context):
   dt = datetime.datetime.utcnow()

   return {
      'statusCode': 200,
      'body': json.dumps({
      'iso_time': dt.strftime('%Y-%m-%dT%H:%M:%SZ')
   })
}
Score: 0

We've used an API from EarthTools with much 6 success:

EarthTools

The service returns XML with information 5 such as the current GMT & timezone offsets 4 (when supplying a latitude & longitude). We 3 used a WebClient in conjunction with an 2 XMLDocument in the VB backend of our ASP.NET 1 page to read & interpret the XML.

Score: 0

Since the service related to the James's answer 13 seems no longer working, I found another 12 good rest API which can be used for this 11 purpose, and it works fine. The source is 10 this site: timeapi and the code that you can use 9 is simply this (using jQuery library and 8 jsonp callback provided by the API):

 $.getJSON("http://www.timeapi.org/utc/now.json?callback=?",function(json){
       //console.log(json)
       alert(json.dateString);
 });

With 7 this you will have the date and hour in 6 the fomat like

  September 02, 2016 09:59:42 GMT+0100

If you want to manipulate 5 it in javascript, to have the hours, just 4 transform it in a Date object like this:

  new Date(json.dateString)

So, for 3 example, you can write like this:

   $.getJSON("http://www.timeapi.org/utc/now.json?callback=?",function(json){

         var now = new Date(json.dateString);
         var hours = now.toLocaleTimeString();

         alert(hours)

    });

in this 2 way you will have the exact local time in 1 hours.

More Related questions