日期:2014-05-20  浏览次数:20969 次

c#2005如何获取网络时间?
c#2005如何获取网络时间?

------解决方案--------------------
using System.Threading; //需要使用多线程
using System.Net; //需要使用网络
using System.Net.Sockets; //需要使用网络。
using System.Runtime.InteropServices;
class Win32API
{
[DllImport( "kernel32.dll ")]
public static extern int SetLocalTime (ref SystemTime lpSystemTime);
}

public struct SystemTime
{
public short wYear;
public short wMonth;
public short wDayOfWeek;
public short wDay;
public short wHour;
public short wMinute;
public short wSecond;
public short wMilliseconds;
}


public class frmMain : System.Windows.Forms.Form
{
////省略自动生成的代码
////……………

Thread thrTimeSync;
private void TimeSyncProc()
{
while(true)
{
TcpClient c = new TcpClient();
c.Connect( "www.time.ac.cn ", 37); //连接到国内授时服务器

NetworkStream s;
s = c.GetStream(); //读取数据流
c.Close();

byte []buf = new byte[4];
s.Read(buf,0,4); //把数据存到数组中

uint lTime;

//把服务器返回数据转换成1900/1/1 UTC 到现在所经过的秒数
lTime = ((uint)buf[0] < < 24) + ((uint)buf[1] < < 16) + ((uint)buf[2] < < 8) + (uint)buf[3];

//得到真实的本地时间
System.DateTime datetime = new DateTime(1900,1,1,0,0,0,0);
datetime = datetime.AddSeconds(lTime).ToLocalTime();

//这里可以显示出时间。有兴趣的朋友可以取消注释看一下效果。
//MessageBox.Show(datetime.ToLongDateString() + datetime.ToLongTimeString());

//修改系统时间
SystemTime sysDateTime = new SystemTime();

sysDateTime.wYear = (short)datetime.Year;
sysDateTime.wDay = (short)datetime.Day;
sysDateTime.wMonth = (short)datetime.Month;

sysDateTime.wHour = (short)datetime.Hour;
sysDateTime.wMinute = (short)datetime.Minute;
sysDateTime.wSecond = (short)datetime.Second;

Win32API.SetLocalTime(ref sysDateTime);

System.Threading.Thread.Sleep(1 * 1000);
}
}

private void frmMain_Load(object sender, System.EventArgs e)
{
thrTimeSync = new Thread(new ThreadStart(TimeSyncProc));
thrTimeSync.Start();
}

private void frmMain_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
thrTimeSync.Abort();
}

}

我也是找的人家的作者是王晓光