一、获取本地时间
System.DateTime.Now
二、获取网络时间
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 FormTime : Form
{
Point CPoint;
int Frm_Height = 0;
int FrmHeight = 0;
static int Tem_place = 0;
public FormTime()
{
InitializeComponent();
}
private void FormTime_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));
}
public DateTime getWebTime()
{
const string ntpServer = "ntp1.aliyun.com";
byte[] ntpData = new byte[48];
ntpData[0] = 0x1B;
IPAddress[] addresses = Dns.GetHostEntry(ntpServer).AddressList;
foreach (var item in addresses)
{
Debug.WriteLine("IP:"+ item);
}
IPEndPoint ipEndPoint = new IPEndPoint(addresses[0], 123);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Connect(ipEndPoint);
socket.ReceiveTimeout = 3000;
socket.Send(ntpData);
socket.Receive(ntpData);
socket.Close();
const byte serverReplyTime = 40;
ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);
ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);
intPart = swapEndian(intPart);
fractPart = swapEndian(fractPart);
ulong milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000UL);
DateTime webTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds(milliseconds);
return webTime.ToLocalTime();
}
public static DateTime DataStandardTime()
{
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());
return dt;
}
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)
{
label_date.Text = DateTime.Now.ToString("F")+" "+DateTime.Now.ToString("fff");
label_dateNet.Text = DateTime.Now.ToString("F");
}
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");
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);
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 利用窗体上的控件移动窗体
public void FrmMove(Form Frm, MouseEventArgs e)
{
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")
{
Application.Exit();
}
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;
}
}
}
}
}