An easy way to syncTime using C#

时间:2023-03-09 20:09:10
An easy way to syncTime using C#
/*
* Created by SharpDevelop.
* User: Administrator
* Date: 2013/10/23
* Time: 8:57
* author zibet
*/
using System;
using System.Net;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace SyncTime
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class MainForm : Form
{
[StructLayout(LayoutKind.Sequential)]
public struct SystemTime
{
public ushort wYear;
public ushort wMonth;
public ushort wDayOfWeek;
public ushort wDay;
public ushort wHour;
public ushort wMinute;
public ushort wSecond;
public ushort wMiliseconds;
}
public MainForm() {
InitializeComponent();
}
[DllImport("Kernel32.dll")]
public static extern bool SetLocalTime(ref SystemTime sysTime);
[DllImport("Kernel32.dll")]
public static extern void GetLocalTime(ref SystemTime localTime);
private DateTime getIntetime(){
return DateTime.Parse(WebRequest.Create("http://www.baidu.com/").GetResponse().Headers.Get("Date"));
}
void MainFormLoad(object sender, EventArgs e)
{
SystemTime st = new SystemTime();
DateTime BJTime = getIntetime();
st.wYear = Convert.ToUInt16(BJTime.Year);
st.wMonth = Convert.ToUInt16(BJTime.Month);
st.wDay = Convert.ToUInt16(BJTime.Day);
st.wHour = Convert.ToUInt16(BJTime.Hour);
st.wMinute = Convert.ToUInt16(BJTime.Minute);
st.wSecond = Convert.ToUInt16(BJTime.Second);
if (!SetLocalTime(ref st)) {
MessageBox.Show("Sync failed T-T");
return;
}
MessageBox.Show("Sync done!"); }
}
}