0
点赞
收藏
分享

微信扫一扫

Unity获取网络时间


/// <summary>获取网络时间</summary>
        public static DateTime GetNetworkTime()
        {
            // NTP服务器地址
            string ntpServer = "time.windows.com";

            // 创建NTP请求
            var ntpRequestData = new byte[48];
            ntpRequestData[0] = 0x1B; // NTP协议版本和模式

            // 发送请求并接收响应
            var ntpClient = new UdpClient(ntpServer, 123);
            ntpClient.Send(ntpRequestData, ntpRequestData.Length);
            IPEndPoint endPoint = null;
            var ntpResponseData = ntpClient.Receive(ref endPoint);

            // 关闭NTP客户端连接
            ntpClient.Close();

            // 从响应数据中解析出时间戳
            ulong timestamp = (ulong)ntpResponseData[40] << 24 | (ulong)ntpResponseData[41] << 16 | (ulong)ntpResponseData[42] << 8 | (ulong)ntpResponseData[43];

            // NTP时间起始日期(1900年1月1日)
            DateTime ntpEpoch = new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            // 计算当前网络时间
            DateTime networkTime = ntpEpoch.AddSeconds(timestamp);

            // 转换为本地时区时间
            DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(networkTime, TimeZoneInfo.Local);

            return localTime;
        }

举报

相关推荐

0 条评论