C#同步收集時光的辦法實例詳解。本站提示廣大學習愛好者:(C#同步收集時光的辦法實例詳解)文章只能為提供參考,不一定能成為您想要的結果。以下是C#同步收集時光的辦法實例詳解正文
本文實例講述了C#同步收集時光的辦法。分享給年夜家供年夜家參考。詳細剖析以下:
客戶的機械的體系時光常常失足,招致給他們做的軟件沒法正常應用,所今後來就加了一個同步收集時光的小功效。完成起來很簡略,然則卻很應用。
這個小功效就是先獲得收集時光,然後將體系的時光修正成從收集取得的時光。上面是詳細的完成:
獲得收集時光:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Net; using System.Net.Sockets; using System.Text.RegularExpressions; using System.Runtime.InteropServices; using System.Runtime; /// <summary> /// 收集時光 /// </summary> public class NetTime { /// <summary> /// 獲得尺度北京時光,讀取http://www.beijing-time.org/time.asp /// </summary> /// <returns>前往收集時光</returns> public DateTime GetBeijingTime() { DateTime dt; WebRequest wrt = null; WebResponse wrp = null; try { wrt = WebRequest.Create("http://www.beijing-time.org/time.asp"); wrp = wrt.GetResponse(); string html = string.Empty; using (Stream stream = wrp.GetResponseStream()) { using (StreamReader sr = new StreamReader(stream,Encoding.UTF8)) { html = sr.ReadToEnd(); } } string[] tempArray = html.Split(';'); for (int i = 0; i < tempArray.Length; i++) { tempArray[i] = tempArray[i].WordStr("\r\n", ""); } string year = tempArray[1].Split('=')[1]; string month = tempArray[2].Split('=')[1]; string day = tempArray[3].Split('=')[1]; string hour = tempArray[5].Split('=')[1]; string minite = tempArray[6].Split('=')[1]; string second = tempArray[7].Split('=')[1]; dt = DateTime.Parse(year + "-" + month + "-" + day + " " + hour + ":" + minite + ":" + second); } catch (WebException) { return DateTime.Parse("2011-1-1"); } catch (Exception) { return DateTime.Parse("2011-1-1"); } finally { if (wrp != null) wrp.Close(); if (wrt != null) wrt.Abort(); } return dt; } }
獲得收集時光,前往一個DateTime對象,然後傳給設置體系時光的辦法,修正體系時光。
同步體系時光:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Net; using System.Net.Sockets; using System.Text.RegularExpressions; using System.Runtime.InteropServices; using System.Runtime; /// <summary> /// 更新體系時光 /// </summary> public class UpdateTime { //設置體系時光的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 SetDate(DateTime dt) { SYSTEMTIME st; st.year = (short)dt.Year; st.month = (short)dt.Month; st.dayOfWeek = (short)dt.DayOfWeek; st.day = (short)dt.Day; st.hour = (short)dt.Hour; st.minute = (short)dt.Minute; st.second = (short)dt.Second; st.milliseconds = (short)dt.Millisecond; bool rt = SetLocalTime(ref st); return rt; } }
兩個辦法分離寫在了兩個類外面,只須要在客戶端實例化兩個對象,然後順次挪用其辦法便可,簡略適用。
願望本文所述對年夜家的C#法式設計有所贊助。