C#获取网络时间

2021-03-09 04:27

阅读:361

标签:net   head   color   ==   creat   cti   final   时间   try   

public static string GetNetDateTime()
        {
            WebRequest request = null;
            WebResponse response = null;
            WebHeaderCollection headerCollection = null;
            string datetime = string.Empty;
            try
            {
                request = WebRequest.Create("https://www.baidu.com");
                request.Timeout = 3000;
                request.Credentials = CredentialCache.DefaultCredentials;
                response = (WebResponse)request.GetResponse();
                headerCollection = response.Headers;
                foreach (var h in headerCollection.AllKeys)
                { if (h == "Date") { datetime = headerCollection[h]; } }
                return datetime;
            }
            catch (Exception) { return datetime; }
            finally
            {
                if (request != null)
                { request.Abort(); }
                if (response != null)
                { response.Close(); }
                if (headerCollection != null)
                { headerCollection.Clear(); }
            }
        }

调用方法:

string dt = GetNetDateTime();
            string dtNow = Convert.ToDateTime(dt).ToString("yyyy-MM-dd HH:mm:ss");

 

C#获取网络时间

标签:net   head   color   ==   creat   cti   final   时间   try   

原文地址:https://www.cnblogs.com/LoveQin/p/12759643.html


评论


亲,登录后才可以留言!