开发者

What is the best way to sync computer time with an internet time server?

开发者 https://www.devze.com 2023-01-12 11:09 出处:网络
I need to get the current time from one of internet time server in my desktop application. I suppose I need something like a request string and a regular expression to get time from any site that user

I need to get the current time from one of internet time server in my desktop application. I suppose I need something like a request string and a regular expression to get time from any site that user wants (may be with several predefined sites).

Or may be there are some free libraries开发者_Go百科 exist?

Thanks.


This is what the Network Time Protocol was built for. But it's probably something best left to your operating system, lest you end up with duelling applications using different, not-quite-synchronised servers.

See the headings in the link above for UNIX and Windows implementations.


There are free libraries and specifications for how to retrieve time, and the format in which you receive it (so REs are generally unnecessary). You choice depends on the level of precision/accuracy you want.

RFC 868 gives time to the second, which is entirely adequate for a lot of people's purposes. If it's good enough, it's a lot simpler to implement than the others listed below.
RFC 5905 defines the Network Time Protocol. As long as you only want to get the time, not provide it for anybody else, NTP is probably overkill though.
RFC 4330 defines SNTP (Simple NTP), which is a simplified version of NTP for computers that act as "leaf nodes" -- i.e., they retrieve time from elsewhere, but nothing else retrieves the time from them.

The NTP project has free NTP libraries for a number of systems.


This feels like something the OS should do on its own...

There is a protocol on the internet called NTP that returns time from timeservers.

You might want to try looking for a library/class that can use NTP to retrieve time for you.

Or you could try looking at the source code for ntpclient.


Usually, most operating systems embeds such a functionality.

Both Windows and Linux can sync with NTP servers.

If really want to let the user change its timezone, you should look for OS specific API's instead of communicating directly with the time servers then changing the system time. This would be way nicer.


Maybe you can take a look at this code and get some inspiration:

http://web.abnormal.com/~thogard/ntp/ntpdate.c

0

精彩评论

暂无评论...
验证码 换一张
取 消