一、配置NTP服务器
1、在局域网内找一台时间可靠的计算机或服务器做为NTP服务器,例IP:209.209.209.2
2、在NTP服务器上运行 regedit 打开注册表

3、在注册表中展开HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer

4、在NtpServer项的右侧键值Enabled,将默认的0改为1,1为启用NTP服务器。

5、HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Config

6、找到Config项右侧的AnnounceFlags,把默认的10改为5

7、在NTP服务器的服务管理器里找到Windows Time 服务,启动此服务并设置为"自动(延时启动)",

8、NTP服务器配置完成
9、当本机系统已配置了时间同步服务器,通过CMD查询连接NTP服务状态及同步信息:w32tm /query /status w32tm /query /peers

二、使用程序进行连接NTP服务同步本地系统时间
1、获取NTP服务器时间 2、同步本地系统时间 (获取同步时间方式有很多可以自主查询实现)
cs
/// <summary>
/// windows系统时间同步(程序执行需要启动管理员权限执行)
/// </summary>
/// <param name="timeServer">时间同步服务器地址/IP</param>
public static void SyncTimeWithServer(string timeServer)
{
try
{
// 配置时间服务器
Process.Start("w32tm", $"/config /syncfromflags:manual /manualpeerlist:{timeServer}").WaitForExit();
// 强制同步时间
Process.Start("w32tm", "/resync").WaitForExit();
Console.WriteLine("时间同步成功!");
}
catch (Exception ex)
{
Console.WriteLine($"时间同步失败: {ex.Message}");
}
}
注意以上配置时间同步服务器是持久性配置,可在如下页面中查看,但是不会定期执行同步,因此需要额外进行定期同步操作