C#/.NET 获取当前的网络时间

C#/.NET 获取当前的网络时间

是通过调用百度首页,去拿它的时间

其中的RestClient 需要在Nuget添加引用RestSharp

        public static DateTime GetWebTime()
        {
            try
            {
                DateTime time = DateTime.MinValue;
                RestClient restClient = new RestClient("https://www.baidu.com");
                var resp = restClient.Get(new RestRequest() { Timeout = 5_000 });
                foreach (var h in resp.Headers)
                {
                    if (h.Name == "Date")
                    {
                        var dt = DateTime.Parse(h.Value.ToString());
                        time = dt.ToUniversalTime().AddHours(8);
                        return time;
                    }
                }
            }
            catch (Exception)
            {
            }
            return DateTime.Now;
        }
发布了190 篇原创文章 · 获赞 298 · 访问量 48万+

猜你喜欢

转载自blog.csdn.net/qq_34202873/article/details/101545474