C#程序中获取百度时间
/// <summary> /// 获取百度时间 /// </summary> /// <returns></returns> 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 = 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(); } } }
调用
var aaa = GetNetDateTime(); var bbb = Convert.ToDateTime(aaa).ToString("yyyy-MM-dd HH:mm:ss"); textBox2.Text = bbb;
测试步骤:
1、在电脑右下角鼠标右键选择“调整日期和时间”
2、关闭“自动设置时间”,点击下发“更改”
3、手动设置一个和当前时间不一致的时间用来测试
4、打开程序,测试即可看到系统时间与电脑时间一致,百度时间与百度查询的时间一致(百度查询时间链接:现在北京时间 在线标准北京时间校对 (beijing-time.org))