码迷,mamicode.com
首页 > Windows程序 > 详细

C#获取网络时间

时间:2020-04-23 12:40:38      阅读:247      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!