using System; using UnityEngine.Networking; using System.Threading.Tasks; using Fort23.UTool; namespace Fort23.Core { public static class NetworkTime { // 百度服务器时间(通过 HTTP Date 头) private static readonly string BaiduUrl = "https://www.baidu.com"; public static async Task GetNetworkTimeAsync() { try { using var www = UnityWebRequest.Head(BaiduUrl); www.timeout = 5; var operation = www.SendWebRequest(); while (!operation.isDone) await Task.Yield(); if (www.result == UnityWebRequest.Result.Success) { string dateHeader = www.GetResponseHeader("Date"); if (!string.IsNullOrEmpty(dateHeader)) { // 解析 RFC 1123 格式的时间字符串 if (DateTime.TryParse(dateHeader, null, System.Globalization.DateTimeStyles.AssumeUniversal, out DateTime serverTime)) { var utcTime = serverTime.ToUniversalTime(); LogTool.Log($"百度服务器时间: {utcTime:yyyy-MM-dd HH:mm:ss} UTC"); return utcTime; } } } else { LogTool.Error($"请求百度失败: {www.error}"); } } catch (Exception e) { LogTool.Error($"[NetworkTime]异常: {e.Message}"); } LogTool.Error("[NetworkTime]获取百度时间失败"); return null; } } }