charlie
charlie

Reputation: 323

Client Side clock using server side system time

Im working in a .Net environment, and on my aspx page I would like to add a running digital clock w//seconds , but I need it to use the server side time. Whats the best approach for this?

Thanks!

Upvotes: 1

Views: 3131

Answers (2)

bevacqua
bevacqua

Reputation: 48476

Take a moment to look at this javascript library.

You would just need to provide your server-side time to your javascript code, probably through something like a data-attribute

i.e:

<html data-server-time="@Model.ServerTime">

and then your JS should simply be (assuming jQuery, and moment):

var date = $('html').data('server-time');
var start = new Date();

var updateTime = function (){
    setTimeout(function(){
        var now = moment(date).add(new Date() - start).format('YYYY/MM/DD HH:mm:ss')
        $('.target').text(now);
        updateTime();
    },1000);
}

$(function(){
    updateTime();
});

Fiddle

This way you would be using the server time but you wouldn't need to request it more than once per page load, avoiding unnecessary AJAX calls. Unless your server has a nuclear grade clock or something like that.

Upvotes: 5

zeroef
zeroef

Reputation: 1959

Have you considered the AJAX UpdatePanel?

MSDN: Tutorial: How to refresh an UpdatePanel control at a timed interval

It might be overkill to update every second. Maybe implement it so that it polls the server to check the server and the client times are still sync'd and if not, update the client page?

Upvotes: 1

Related Questions