c# 修改客戶端的機器時間


在程序中修改客戶端的機器時間,我認為有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));
        }

    }

 最后,把這個類上傳上來

View Code
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,全部完事,並非原創,本人代碼也比較粗糙,功能很實用.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM