当前位置: > 热博

新哥:c#怎么获得网络标准日期和时间

时间:2022-04-19 03:36:01 热博 我要投稿

澳斯丹的回答:

1、获取网络日期时间 ///?

?? ///?获取网络日期时间?? ///?

?? ///?

?? 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();?}?? ????}?? }2、调用 string?dt?=?GetNetDateTime();?? Console.WriteLine(Convert.ToDateTime(dt).ToString("yyyy-MM-dd?HH:mm:ss"));?? Console.ReadLine();

一见不钟情的回答: