C#获取网络时间
2021-03-09 04:27
标签:net head color == creat cti final 时间 try 调用方法: C#获取网络时间 标签:net head color == creat cti final 时间 try 原文地址:https://www.cnblogs.com/LoveQin/p/12759643.htmlpublic 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");