之前写过一篇博客,是关于系统时间不准的。本来以为按照那个教程就没问题了,没想到还是不准。查了下,那个Windows Time的进程还是被关掉了(估计是腾讯的电脑管家搞的鬼)。既然它总是被关,我们就直接写一个同步程序吧。这对程序员来说,这都不是事儿
1、从网络获取时间
要同步时间,先要确定从哪里同步?其实一般的大网站都是可以的,我是从百度上同步的,我们任意调用一个网站,都会返回Date的值,直接用这个就可以
/// <summary> /// 从网络上获取北京时间 /// </summary> /// <returns></returns> public static DateTime? GetPublicTime() { //参考地址 //https://blog.csdn.net/qq_34090937/article/details/116616381?spm=1001.2101.3001.6650.2 //以下网站也可以 //String webUrl1 = "http://www.bjtime.cn";//bjTime //String webUrl2 = "http://www.baidu.com";//百度 //String webUrl3 = "http://www.taobao.com";//淘宝 //String webUrl4 = "http://www.ntsc.ac.cn";//中国科学院国家授时中心 //String webUrl5 = "http://www.360.cn";//360 //String webUrl6 = "http://www.beijing-time.org";//beijing-time DateTime? dtmTime = null; WebRequest request = WebRequest.Create("https://www.baidu.com"); request.Timeout = 1000; request.Credentials = CredentialCache.DefaultCredentials; WebResponse response = (WebResponse)request.GetResponse(); WebHeaderCollection headerCollection = response.Headers; foreach (var h in headerCollection.AllKeys) { if (h == "Date") { string sDtm = headerCollection[h]; dtmTime = DateTime.Parse(sDtm); break; } } return dtmTime; }
2、同步本地时间
这里要用到系统API的,C#本身是没有提供函数。引入成功后,再调用一下就OK了。
//设置系统时间的API函数 [DllImport("kernel32.dll")] private static extern bool SetLocalTime(ref SYSTEMTIME time); [StructLayout(LayoutKind.Sequential)] private struct SYSTEMTIME { public short year; public short month; public short dayOfWeek; public short day; public short hour; public short minute; public short second; public short milliseconds; } /// <summary> /// 设置本地时间 /// </summary> /// <param name="dt">需要设置的时间</param> /// <returns>返回系统时间设置状态,true为成功,false为失败</returns> public static bool SetLocalTime(DateTime dtm) { SYSTEMTIME st; st.year = (short)dtm.Year; st.month = (short)dtm.Month; st.dayOfWeek = (short)dtm.DayOfWeek; st.day = (short)dtm.Day; st.hour = (short)dtm.Hour; st.minute = (short)dtm.Minute; st.second = (short)dtm.Second; st.milliseconds = (short)dtm.Millisecond; bool rt = SetLocalTime(ref st); return rt; }
功能完成后,可以写到Windows服务里,如果觉得复杂。就写一个小的Winform程序,页面里使用timer定时器,也能做到。每隔1小时刷一次,系统时间基本就准确了
文章评论