c# 修改客户端的机器时间
2012-10-19 11:19 河蟹社会 阅读(1695) 评论(18) 编辑 收藏 举报在程序中修改客户端的机器时间,我认为有2种方法:
1,用命令方式.net time. 由于本人比较愚笨,这种方法木有学会.
2,获取一个网络时间,然后修改. 这里就比较简单,容易理解了, 这里用win32的方法修改机器时间.那么,怎么获取网络时间呢,这里又可以分成2种方法,一中是直接读取一个url,获取内容,然后转换成我们需要时间,第二种是socket,连接服务器,读取数据流.
我在项目中,运用的第二种方法来修改客户端的机器时间.获取网络时间,用的是第一种,读取url方式.
#region 获取北京时间 /// <summary> /// 获取北京时间 /// </summary> /// <returns></returns> public static DateTime GetBjDatetime() { try { //http://www.beijing-time.org/time.asp string html = string.Empty; try { html = FetchUrl("自己网站的一个地址,提供数据输出", Encoding.UTF8); } catch { html = FetchUrl("http://www.beijing-time.org/time.asp", Encoding.UTF8); } string year = RegexMatch(html, "nyear="); string month = RegexMatch(html, "nmonth="); string day = RegexMatch(html, "nday="); string hour = RegexMatch(html, "nhrs="); string minite = RegexMatch(html, "nmin="); string second = RegexMatch(html, "nsec="); DateTime dt = DateTime.Parse(year + "-" + month + "-" + day + " " + hour + ":" + minite + ":" + second); return dt; } catch (Exception ex) { throw ex; } } private static string RegexMatch(string originalText, string patternStr) { Match m = Regex.Match(originalText, patternStr + "(?<v>\\d+);", RegexOptions.IgnoreCase); return m.Success ? m.Groups["v"].ToString() : string.Empty; } private static string FetchUrl(string url, Encoding coding) { HttpWebRequest request = null; HttpWebResponse response = null; Stream stm = null; StreamReader reader = null; try { request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = 1000 * 3;//设置超时时间为3秒 response = (HttpWebResponse)request.GetResponse(); stm = response.GetResponseStream(); reader = new StreamReader(stm, coding); string content = reader.ReadToEnd(); return content; } catch (Exception exp) { throw exp; } finally { if (reader != null) reader.Close(); if (stm != null) stm.Close(); if (response != null) response.Close(); } } #endregion
还有一种socket获取网络时间代码也贴出来
/// <summary> /// tcp 获取网络时间 /// </summary> /// <returns></returns> public static DateTime GetNetworkTime() { System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(); client.Connect("132.163.4.102", 13); System.Net.Sockets.NetworkStream ns = client.GetStream(); byte[] bytes = new byte[1024]; int bytesRead = 0; bytesRead = ns.Read(bytes, 0, bytes.Length); client.Close(); char[] sp = new char[1]; sp[0] = ' '; DateTime dt = new DateTime(); string str1; str1 = System.Text.Encoding.ASCII.GetString(bytes, 0, bytesRead); string[] s; s = str1.Split(sp); if (s.Length >= 2) { dt = System.DateTime.Parse(s[1] + " " + s[2]);//得到标准时间 dt = dt.AddHours(8);//得到北京时间 } return dt; }
下面是win32方法修改本机时间
[StructLayout(LayoutKind.Sequential)] public class SystemTime { public ushort year; public ushort month; public ushort dayofweek; public ushort day; public ushort hour; public ushort minute; public ushort second; public ushort milliseconds; public SystemTime(ushort _year, ushort _month, ushort _dayofweek, ushort _day, ushort _hour, ushort _minute, ushort _second, ushort _milliseconds) { this.year = _year; this.month = _month; this.dayofweek = _dayofweek; this.day = _day; this.hour = _hour; this.minute = _minute; this.second = _second; this.milliseconds = _milliseconds; } } public class ReSetLocalTimeFromNetwork { [DllImport("Kernel32.dll", SetLastError = true)] private static extern Boolean SetLocalTime([In, Out] SystemTime st); [DllImport("kernel32", SetLastError = true)] private static extern int GetLastError(); /// <summary> /// 设置系统时间 /// </summary> /// <param name="newdatetime">新时间</param> /// <returns></returns> private static bool SetSysTime(SystemTime sysTime) { bool flag = SetLocalTime(sysTime); if (flag == false) { int intValue = GetLastError(); throw new Exception(intValue.ToString() + " error, can't set local time."); } return flag; } /// <summary> /// 转换时间 /// </summary> /// <param name="dt"></param> /// <returns></returns> public static SystemTime ConvertDatetime(DateTime dt) { return new SystemTime(Convert.ToUInt16(dt.Year), Convert.ToUInt16(dt.Month), Convert.ToUInt16(dt.DayOfWeek) , Convert.ToUInt16(dt.Day), Convert.ToUInt16(dt.Hour), Convert.ToUInt16(dt.Minute), Convert.ToUInt16(dt.Second), Convert.ToUInt16(dt.Millisecond)); } }
最后,把这个类上传上来
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Runtime.InteropServices; using System.Net.Sockets; using System.Net; using System.IO; namespace Somnus { [StructLayout(LayoutKind.Sequential)] public class SystemTime { public ushort year; public ushort month; public ushort dayofweek; public ushort day; public ushort hour; public ushort minute; public ushort second; public ushort milliseconds; public SystemTime(ushort _year, ushort _month, ushort _dayofweek, ushort _day, ushort _hour, ushort _minute, ushort _second, ushort _milliseconds) { this.year = _year; this.month = _month; this.dayofweek = _dayofweek; this.day = _day; this.hour = _hour; this.minute = _minute; this.second = _second; this.milliseconds = _milliseconds; } } public class ReSetLocalTimeFromNetwork { [DllImport("Kernel32.dll", SetLastError = true)] private static extern Boolean SetLocalTime([In, Out] SystemTime st); [DllImport("kernel32", SetLastError = true)] private static extern int GetLastError(); public static bool SetSysTime() { return SetSysTime(ConvertDatetime(GetBjDatetime())); } /// <summary> /// 设置系统时间 /// </summary> /// <param name="newdatetime">新时间</param> /// <returns></returns> private static bool SetSysTime(SystemTime sysTime) { bool flag = SetLocalTime(sysTime); if (flag == false) { int intValue = GetLastError(); throw new Exception(intValue.ToString() + " error, can't set local time."); } return flag; } /// <summary> /// 转换时间 /// </summary> /// <param name="dt"></param> /// <returns></returns> public static SystemTime ConvertDatetime(DateTime dt) { return new SystemTime(Convert.ToUInt16(dt.Year), Convert.ToUInt16(dt.Month), Convert.ToUInt16(dt.DayOfWeek) , Convert.ToUInt16(dt.Day), Convert.ToUInt16(dt.Hour), Convert.ToUInt16(dt.Minute), Convert.ToUInt16(dt.Second), Convert.ToUInt16(dt.Millisecond)); } #region 获取北京时间 /// <summary> /// 获取北京时间 /// </summary> /// <returns></returns> public static DateTime GetBjDatetime() { try { //http://www.beijing-time.org/time.asp string html = string.Empty; try { html = FetchUrl("自己的网站输出一个时间", Encoding.UTF8); } catch { html = FetchUrl("http://www.beijing-time.org/time.asp", Encoding.UTF8); } string year = RegexMatch(html, "nyear="); string month = RegexMatch(html, "nmonth="); string day = RegexMatch(html, "nday="); string hour = RegexMatch(html, "nhrs="); string minite = RegexMatch(html, "nmin="); string second = RegexMatch(html, "nsec="); DateTime dt = DateTime.Parse(year + "-" + month + "-" + day + " " + hour + ":" + minite + ":" + second); return dt; } catch (Exception ex) { throw ex; } } private static string RegexMatch(string originalText, string patternStr) { Match m = Regex.Match(originalText, patternStr + "(?<v>\\d+);", RegexOptions.IgnoreCase); return m.Success ? m.Groups["v"].ToString() : string.Empty; } private static string FetchUrl(string url, Encoding coding) { HttpWebRequest request = null; HttpWebResponse response = null; Stream stm = null; StreamReader reader = null; try { request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = 1000 * 3;//设置超时时间为3秒 response = (HttpWebResponse)request.GetResponse(); stm = response.GetResponseStream(); reader = new StreamReader(stm, coding); string content = reader.ReadToEnd(); return content; } catch (Exception exp) { throw exp; } finally { if (reader != null) reader.Close(); if (stm != null) stm.Close(); if (response != null) response.Close(); } } /// <summary> /// tcp 获取网络时间 /// </summary> /// <returns></returns> public static DateTime GetNetworkTime() { System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(); client.Connect("132.163.4.102", 13); System.Net.Sockets.NetworkStream ns = client.GetStream(); byte[] bytes = new byte[1024]; int bytesRead = 0; bytesRead = ns.Read(bytes, 0, bytes.Length); client.Close(); char[] sp = new char[1]; sp[0] = ' '; DateTime dt = new DateTime(); string str1; str1 = System.Text.Encoding.ASCII.GetString(bytes, 0, bytesRead); string[] s; s = str1.Split(sp); if (s.Length >= 2) { dt = System.DateTime.Parse(s[1] + " " + s[2]);//得到标准时间 dt = dt.AddHours(8);//得到北京时间 } return dt; } #endregion } }
OK,全部完事,并非原创,本人代码也比较粗糙,功能很实用.