C# 实现获取网络时间

C# Winform获取网络时间,同时显示本地时间,支持毫秒显示


直接上图

时间同步
工具下载

代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Diagnostics;
using System.Net;
using System.Net.Sockets;

using System.Runtime;
using System.Runtime.InteropServices;
using System.Drawing.Drawing2D;

namespace WindowsFormsTimer
{
    public partial class Form1 : Form
    {

        Point CPoint;//获取控件中鼠标的坐标
        int Frm_Height = 0;
        int FrmHeight = 0;
        static int Tem_place = 0;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            timer.Start();

            Frm_Height = this.Height;
            FrmHeight = this.Height;


            button_Click(null, null);
        }

        // 小端存储与大端存储的转换
        private uint swapEndian(ulong x)
        {
            return (uint)(((x & 0x000000ff) << 24) +
            ((x & 0x0000ff00) << 8) +
            ((x & 0x00ff0000) >> 8) +
            ((x & 0xff000000) >> 24));
        }

        // 方法1、获取NTP网络时间
        public DateTime getWebTime()
        {
            // default ntp server
            const string ntpServer = "ntp1.aliyun.com";
 
            // NTP message size - 16 bytes of the digest (RFC 2030)
            byte[] ntpData = new byte[48];
            // Setting the Leap Indicator, Version Number and Mode values
            ntpData[0] = 0x1B; // LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)
               
            IPAddress[] addresses = Dns.GetHostEntry(ntpServer).AddressList;
            foreach (var item in addresses)
            {
                Debug.WriteLine("IP:"+ item); 
            }
            
            // The UDP port number assigned to NTP is 123
            IPEndPoint ipEndPoint = new IPEndPoint(addresses[0], 123);
            
            // NTP uses UDP
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            socket.Connect(ipEndPoint);
            // Stops code hang if NTP is blocked
            socket.ReceiveTimeout = 3000;
            socket.Send(ntpData);
            socket.Receive(ntpData);
            socket.Close();
 
            // Offset to get to the "Transmit Timestamp" field (time at which the reply 
            // departed the server for the client, in 64-bit timestamp format."
            const byte serverReplyTime = 40;
            // Get the seconds part
            ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);
            // Get the seconds fraction
            ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);
            // Convert From big-endian to little-endian
            intPart = swapEndian(intPart);
            fractPart = swapEndian(fractPart);
            ulong milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000UL);
 
            // UTC time
            DateTime webTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds(milliseconds);
            // Local time
            return webTime.ToLocalTime();
        }

        //方法2、获取ntp时间
        public static DateTime DataStandardTime()//使用时,将static 关键字删除,在其它位置方可使用?2010-11-24
        {//返回国际标准时间
            //只使用的TimerServer的IP地址,未使用域名
            string[,] TimerServer = new string[14, 2];
            int[] ServerTab = new int[] { 3, 2, 4, 8, 9, 6, 11, 5, 10, 0, 1, 7, 12 };

            TimerServer[0, 0] = "time-a.nist.gov";
            TimerServer[0, 1] = "129.6.15.28";
            TimerServer[1, 0] = "time-b.nist.gov";
            TimerServer[1, 1] = "129.6.15.29";
            TimerServer[2, 0] = "time-a.timefreq.bldrdoc.gov";
            TimerServer[2, 1] = "132.163.4.101";
            TimerServer[3, 0] = "time-b.timefreq.bldrdoc.gov";
            TimerServer[3, 1] = "132.163.4.102";
            TimerServer[4, 0] = "time-c.timefreq.bldrdoc.gov";
            TimerServer[4, 1] = "132.163.4.103";
            TimerServer[5, 0] = "utcnist.colorado.edu";
            TimerServer[5, 1] = "128.138.140.44";
            TimerServer[6, 0] = "time.nist.gov";
            TimerServer[6, 1] = "192.43.244.18";
            TimerServer[7, 0] = "time-nw.nist.gov";
            TimerServer[7, 1] = "131.107.1.10";
            TimerServer[8, 0] = "nist1.symmetricom.com";
            TimerServer[8, 1] = "69.25.96.13";
            TimerServer[9, 0] = "nist1-dc.glassey.com";
            TimerServer[9, 1] = "216.200.93.8";
            TimerServer[10, 0] = "nist1-ny.glassey.com";
            TimerServer[10, 1] = "208.184.49.9";
            TimerServer[11, 0] = "nist1-sj.glassey.com";
            TimerServer[11, 1] = "207.126.98.204";
            TimerServer[12, 0] = "nist1.aol-ca.truetime.com";
            TimerServer[12, 1] = "207.200.81.113";
            TimerServer[13, 0] = "nist1.aol-va.truetime.com";
            TimerServer[13, 1] = "64.236.96.53";
            int portNum = 13;
            string hostName;
            byte[] bytes = new byte[1024];
            int bytesRead = 0;
            System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
            for (int i = 0; i < 13; i++)
            {
                hostName = TimerServer[ServerTab[i], 0];

                Debug.WriteLine("hostName:"+hostName);
                try
                {
                    client.Connect(hostName, portNum);

                    System.Net.Sockets.NetworkStream ns = client.GetStream();
                    bytesRead = ns.Read(bytes, 0, bytes.Length);
                    client.Close();
                    break;
                }
                catch (System.Exception)
                {
                    Debug.WriteLine("错误!");
                }
            }
            char[] sp = new char[1];
            sp[0] = ' ';
            System.DateTime dt = new DateTime();
            string str1;
            str1 = System.Text.Encoding.ASCII.GetString(bytes, 0, bytesRead);
            Debug.WriteLine("ntp time:"+str1);

            string[] s;
            s = str1.Split(sp);
            dt = System.DateTime.Parse(s[1] + " " + s[2]);//得到标准时间
            Debug.WriteLine("get:"+dt.ToShortTimeString());
            //dt=dt.AddHours (8);//得到北京时间*/
            return dt;

        }

        //方法3、获取网页时间

        //Bdpagetype:2
        //Bdqid:0xaff4e50f00011b53
        //Cache-Control:private
        //Connection:Keep-Alive
        //Content-Encoding:gzip
        //Content-Type:text/html;charset=utf-8
        //Date:Tue, 23 Oct 2018 03:24:38 GMTv
        public static string GetNetDateTime()
        {
            WebRequest request = null;
            WebResponse response = null;
            WebHeaderCollection headerCollection = null;
            string datetime = string.Empty;
            try
            {
                request = WebRequest.Create("https://www.baidu.com");
                request.Timeout = 1000;
                request.Credentials = CredentialCache.DefaultCredentials;
                response = (WebResponse)request.GetResponse();
                headerCollection = response.Headers;
                foreach (var h in headerCollection.AllKeys)
                { if (h == "Date") { datetime = headerCollection[h]; } }
                return datetime;
            }
            catch (Exception) { return datetime; }
            finally
            {
                if (request != null)
                { request.Abort(); }
                if (response != null)
                { response.Close(); }
                if (headerCollection != null)
                { headerCollection.Clear(); }
            }
        }



        private void timer_tick(object sender, EventArgs e)
        {

            // Debug.WriteLine("1s");
            label_date.Text = DateTime.Now.ToString("F")+" "+DateTime.Now.ToString("fff");

            label_dateNet.Text = DateTime.Now.ToString("F"); // +" " + DateTime.Now.ToString("fff");
        }

        private void formClosed(object sender, FormClosedEventArgs e)
        {
            timer.Stop();
            timer1.Stop();
        }

        private void button_Click(object sender, EventArgs e)
        {
            DateTime dt = getWebTime();

            SetDate(dt);
            string str = dt.ToString("F");// +" " + dt.ToString("fff");

            Debug.WriteLine(str);

            label_dateNet.Text = str;
        }


        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;
        }
        [DllImport("kernel32.dll")]
        private static extern bool SetLocalTime(ref SYSTEMTIME time);
        /// <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;
        }

        private void checkBoxClick(object sender, EventArgs e)
        {
            Debug.WriteLine("自动"+checkBox1.Checked);
            if (checkBox1.Checked == true)
            {
                timer1.Start();
                button1.Enabled = false;
            }
            else
            {
                timer1.Stop();
                button1.Enabled = true;
            }

        }

        private void timer1_tick(object sender, EventArgs e)
        {
            Debug.WriteLine("自动更新");
            button_Click(null,null);
        }


        #region  利用窗体上的控件移动窗体
        /// <summary>
        /// 利用控件移动窗体
        /// </summary>
        /// <param Frm="Form">窗体</param>
        /// <param e="MouseEventArgs">控件的移动事件</param>
        public void FrmMove(Form Frm, MouseEventArgs e)  //Form或MouseEventArgs添加命名空间using System.Windows.Forms;
        {
            if (e.Button == MouseButtons.Left)
            {
                Point myPosittion = Control.MousePosition;//获取当前鼠标的屏幕坐标
                myPosittion.Offset(CPoint.X, CPoint.Y);//重载当前鼠标的位置
                Frm.DesktopLocation = myPosittion;//设置当前窗体在屏幕上的位置
                Tem_place = 0;
                this.Height = FrmHeight;
            }
        }
        #endregion

        private void panelMouseDown(object sender, MouseEventArgs e)
        {
            CPoint = new Point(-e.X, -e.Y);
            Debug.WriteLine("mouse down:" + -e.X + " " + -e.Y);
        }


        private void panelMouseMove(object sender, MouseEventArgs e)
        {
            FrmMove(this, e);
        }
        private void mouseMove(object sender, MouseEventArgs e)
        {
            Debug.WriteLine(sender.ToString() +"mouse move:");
            
            PictureBox pictureBox = (PictureBox)sender;

            if (pictureBox.Name == "pictureBoxClose")
            {
                pictureBoxClose.BackgroundImage = global::WindowsFormsTimer.Properties.Resources.close_32px_leave;
            }
        }

        private void mouseLeave(object sender, EventArgs e)
        {
            PictureBox pictureBox = (PictureBox)sender;

            if (pictureBox.Name == "pictureBoxClose")
            {
                pictureBoxClose.BackgroundImage = global::WindowsFormsTimer.Properties.Resources.close_32px;
            }

        }

        private void pictureBox_Click(object sender, EventArgs e)
        {
            PictureBox pictureBox = (PictureBox)sender;
            if (pictureBox.Name == "pictureBoxClose")
            {
                //this.Close();   //只是关闭当前窗口,若不是主窗体的话,是无法退出程序的,另外若有托管线程(非主线程),也无法干净地退出;\
                Application.Exit();  //强制所有消息中止,退出所有的窗体,但是若有托管线程(非主线程),也无法干净地退出;
                //Application.ExitThread(); //强制中止调用线程上的所有消息,同样面临其它线程无法正确退出的问题;
                //System.Environment.Exit(0);   //这是最彻底的退出方式,不管什么线程都被强制退出,把程序结束的很干净。  强烈推荐
            }
            else if (pictureBox.Name == "pictureBoxLock")
            {
                this.TopMost = !this.TopMost;
                if (this.TopMost == true)
                {
                    pictureBoxLock.BackgroundImage = global::WindowsFormsTimer.Properties.Resources.lock_32px;
                }
                else
                {
                    pictureBoxLock.BackgroundImage = global::WindowsFormsTimer.Properties.Resources.unlock_32px;
                }
            }
        }

    }
}

  • 7
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
时间同步服务器是一种用于确保服务器系统时间与标准时间保持一致的重要工具。时间同步常常用于网络中的各个服务器,以确保它们之间的时间是一致的。具体到某个服务器c的时间同步,可以通过以下几个步骤来进行。 首先,服务器c需要与一个可靠的时间源进行连接,该时间源可以是国家授时中心、网络时间协议服务器(NTP服务器)或其他可靠的时间服务器。服务器c可以通过网络连接到时间源,以获取准确的时间信息。 然后,服务器c需要配置时间同步软件,比如NTP(网络时间协议)客户端。NTP是一种常用的时间同步协议,可以确保服务器系统与时间源之间的时间同步。服务器c可以通过安装和配置NTP客户端软件来实现时间同步。 接下来,服务器c需要设置好时间同步的参数。这些参数包括时间同步间隔、时间源的地址等。服务器c可以根据具体需求设置不同的时间同步参数,以满足服务器系统的时间同步需求。 最后,服务器c需要启动时间同步服务,以确保时间同步的持续性。服务器c可以将时间同步服务设置为自启动,以在服务器启动时自动进行时间同步。 总之,通过以上这些步骤,服务器c可以实现时间源的时间同步。通过时间同步,服务器c可以确保其系统时间与标准时间保持一致,从而提高系统的精确性和可靠性。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值