Skip to content Skip to sidebar Skip to footer

Set Javascript Time With Php Server Time?

I have a situation where I want the server time to be displayed on a web page. At present I keep it simple and just do this This works great

Solution 1:

Here is a jQuery plugin for displaying a clock:

http://plugins.jquery.com/project/jqClock

Just initialize it using the time coming back from the server. It automatically updates every second on the client side.

Solution 2:

Try this:

<javascript>
var ctime = '<?phpecho date ("g:i a"); ?>';
</javascript>

Then let a timer increase the value on the javascript side. It's not very precise, but if I saw that right you need minutes only, not seconds, so precision is probably not an issue.

Solution 3:

Use your base-time to calculate the current time on the fly (without using any additional and potentially slow/expensive request; it does not even require jQuery):

var getServerTime = (function () {
    var baseTime = <?phpecho time() * 1000; /* convert to milliseconds */?>,
        startTime = new Date().getTime();

    returnfunction () {
        return baseTime + (new Date().getTime() - startTime);
    };
}());

This function returns the current time (in milliseconds) based on the server-side time. You can update your site an a regular interval and use this function to determine the current server-side time like this:

// update the site every minutesetInterval(function () {
    var currentServerTime = getServerTime();
    // update everything (format date or something)
}, 60 * 1000);

Solution 4:

I believe you can easily find some javascript code over the internet which shows a running clock on your site. On load of the page have PHP set the initial start time for this javascript snippet and i believe you are good to go.

Post a Comment for "Set Javascript Time With Php Server Time?"