3

How can I get the web-server time using jQuery?

Yi Jiang
  • 49,435
  • 16
  • 136
  • 136
Pushpendra
  • 4,344
  • 5
  • 36
  • 64

4 Answers4

17

Here's a way that may work without any particular code, or even a valid path, on the server side.

try {
  var date = new Date($.ajax({'type': 'HEAD', 'url': '/'}).getResponseHeader('Date'));
}
catch(err) { 
  var date = null;
}

This is presumptive that the server will always return a "Date" header. Some experimentation with the particulars of your server will be necessary.

EDIT TO ADD: Note that this is more of a cutesy hackish way to do this. The "correct" way would be to set up a server-side script to return the server time quickly, or possibly put it inline to the page where the script will be running, or simply use the client-side time if it would be "good enough."

Garrett Albright
  • 2,844
  • 3
  • 26
  • 45
  • Kudos! This is a hack, but it's the only solution if you don't have access to server side code, like in some restricted hosting. – Andrey Feb 05 '11 at 01:57
  • 1
    Nice approach :) , and a HEAD-request may be an option to save bandwidth – Dr.Molle Feb 05 '11 at 02:07
  • I didn't think there was a way to do any sort of request other than GET or POST using $.ajax(), but it turns out there *is* a way. I've amended my code so that it does a HEAD request. This adds an additional caveat, however, in that I occasionally encounter servers which do not respond to HEAD requests correctly. – Garrett Albright Feb 05 '11 at 02:17
3

To get server code, you'll need to have some method on server-side that would either add time to the page while rendering, or if you need real-time time (ops), you need to make an ajax call to server using jQuery. That means that you need to have something on server side that would respond to ajax request. What language are you using for server side?

Andrey
  • 20,487
  • 26
  • 108
  • 176
3

If you've got something like php running on your server you could just put something like this to set the date/time by embedding it into the script:

<script>
  var date = new Date("<?php echo date("Y-m-d H:i:s"); ?>");
  alert(date);
</script>
grdaneault
  • 830
  • 1
  • 11
  • 21
2

used Garrett answer, but $.ajax has a short response time, which means its 'getResponseHeader' method cannot be called immediately.

I think this can be a fix:

var Date1 = null;
var endInterval;
function DoJob() {
    if (Date1 == null) {
        if (endInterval)
            clearInterval(endInterval);
        endInterval = setInterval(DoJob, 100);
        return;
    }
    /*
        job to do...
    */
    if (endInterval)
        clearInterval(endInterval);
}
try {
    var oHead = $.ajax({ 'type': 'HEAD', 'url': '/' }).success(function () {
        Date1 = new Date(oHead.getResponseHeader('Date'));
    });
}
catch (err) {
    Date1 = null;
}
DoJob();
Mahyar
  • 681
  • 6
  • 12