C#实现从网络同步标准北京时间的方法
程序员文章站
2023-11-29 17:12:22
本文实例讲述了c#实现从网络同步标准北京时间的方法。分享给大家供大家参考。具体分析如下:
这段c#代码可以从http://www.time.ac.cn网站上获取标准的北京...
本文实例讲述了c#实现从网络同步标准北京时间的方法。分享给大家供大家参考。具体分析如下:
这段c#代码可以从http://www.time.ac.cn网站上获取标准的北京时间,只需简单的组合即可让本地服务器实时同步正确的北京时间
#region /// <summary> /// 获取标准北京时间 /// /// </summary> /// /// <returns></returns> /// public static datetime getstandardtime() { /// //<?xml version="1.0" encoding="gb2312" ?> //- <ntsc> //- <time> // <year>2013</year> // <month>8</month> // <day>29</day> // <weekday /> // <hour>16</hour> // <minite>29</minite> // <second>12</second> // <millisecond /> // </time> // </ntsc> datetime dt; webrequest wrt = null; webresponse wrp = null; try { wrt = webrequest.create("http://www.time.ac.cn/timeflash.asp?user=flash"); wrt.credentials = credentialcache.defaultcredentials; wrp = wrt.getresponse(); streamreader sr = new streamreader(wrp.getresponsestream(),encoding.utf8); string html = sr.readtoend(); sr.close(); wrp.close(); int yearindex = html.indexof("<year>") + 6; int monthindex = html.indexof("<month>") + 7; int dayindex = html.indexof("<day>") + 5; int hourindex = html.indexof("<hour>") + 6; int miniteindex = html.indexof("<minite>") + 8; int secondindex = html.indexof("<second>") + 8; string year = html.substring(yearindex, html.indexof("</year>") - yearindex); string month = html.substring(monthindex, html.indexof("</month>") - monthindex); string day = html.substring(dayindex, html.indexof("</day>") - dayindex); string hour = html.substring(hourindex, html.indexof("</hour>") - hourindex); string minite = html.substring(miniteindex, html.indexof("</minite>") - miniteindex); string second = html.substring(secondindex, html.indexof("</second>") - secondindex); dt = datetime.parse(year + "-" + month + "-" + day + " " + hour + ":" + minite + ":" + second); } catch (webexception) { return datetime.parse("2013-1-1"); } catch (exception) { return datetime.parse("2013-1-1"); } finally { if (wrp != null) wrp.close(); if (wrt != null) wrt.abort(); } return dt; } #endregion
希望本文所述对大家的c#程序设计有所帮助。