1.获取网络时间
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace WIFI_TCP_test
{
class GetNetDateTime
{
/// <summary>
/// 获取网络日期时间
/// </summary>
/// <returns></returns>
public 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(); }
}
}
}
}
2.添加Timer1控件设置为刷新时间为1000ms
3.调用
metroLabel3.Text = Convert.ToDateTime(datetime.GetNetDateTimes()).ToString("yyyy - MM - dd HH: mm:ss");