简体   繁体   中英

How to synchronize DateTime.Now with a NTP server?

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM