c# 获取当前时间
void Main() { var time = GetNetworkTime(); time.Dump(); } public static DateTime GetNetworkTime(string ntpServer = "cn.pool.ntp.org") { try { // NTP消息结构(48字节) byte[] ntpData = new byte[48]; ntpData[0] = 0x1B; // 设置协议版本和模式 // 创建UDP客户端 using (var socket = new UdpClient(ntpServer, 123)) { socket.Send(ntpData, ntpData.Length); IPEndPoint remoteEP = null; ntpData = socket.Receive(ref remoteEP); } // 解析NTP时间戳(从第40字节开始) ulong intPart = (ulong)ntpData[40] << 24 | (ulong)ntpData[41] << 16 | (ulong)ntpData[42] << 8 | ntpData[43]; ulong fractPart = (ulong)ntpData[44] << 24 | (ulong)ntpData[45] << 16 | (ulong)ntpData[46] << 8 | ntpData[47]; // 转换为UNIX时间戳(1900年1月1日 → 1970年1月1日) ulong milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L); var networkTime = new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc) .AddMilliseconds(milliseconds); return networkTime.ToLocalTime(); } catch (Exception ex) { Console.WriteLine($"获取网络时间失败: {ex.Message}"); return DateTime.Now; // 失败时返回本地时间 } }
桂棹兮兰桨,击空明兮溯流光。
浙公网安备 33010602011771号