How to synchronize DateTime.Now with a NTP server?

Davud Aga picture Davud Aga · Oct 1, 2014 · Viewed 7.5k times · Source

I have a NTP-Server and I am getting the date like below:

DateTime NTPDateTime = GetServerTime(); //GetServerTime returns a new DateTime

but my problem is, I only get the current time from ntp-server but cannot update it after without reconnecting to the NTP-Server.

I have tried to do it in a thread like (1000ms interval)

string displayTime() {
   this.lblServerTime.Text = NTPDateTime.ToLongTimeString();
}

It always shows the same DateTime as expected. Like (01.10.2014 - 15:31:25)

But how can I update the DateTime so that it always gives me the current DateTime?

Example if I use the following code, it gives me the current local time

//in a thread
string displayTime() {
   this.lblServerTime.Text = DateTime.Now.ToLongTimeString();
}

But I need the server time and not localtime. and my problem is that I cannot get it everysecond.

is there a way to do it , without a new connection every second to the ntp-server? I have more then 500 client applications which needs server time.

Answer

Patrick Hofman picture Patrick Hofman · Oct 1, 2014

You can't without keeping polling it. The time on the server can change more or less than the local PC time, so you have to do a sync on every refresh.

Another option is to configure the PC to do a regular sync with the NTP server, and use the local time as the 'server time'.

You can't set DateTime.Now to the server time as you may want to.

The last option I can think of is to do a sync every minute or so, and keep the difference between local and server in memory, and adding it to the displayed time.

TimeSpan serverTimeDifference = GetServerTimeDifference();

DateTime actualTime = DateTime.Now + serverTimeDifference;

Where GetServerTimeDifference is:

private static TimeSpan GetServerTimeDifference()
{
    return GetServerTime() - DateTime.Now;
}