c#2005如何获取网络时间?
解决方案 »
- 问题窗体与用户控件传值的问题,求大神
- exe 与dll
- .NET3.5安装问题
- 现在下载哪个devexpress for vs2005的控件包能
- 假设一个字符串str="4*36+7+88/12^2",C#如何直接计算出这个字符串变量str的算术值。
- 怎样在DataGrid中实现数量,金额合计???
- 请教一个基本问题
- 发布免费软件:Contact.Net V1.0 --个人关系管理,欢迎使用哈! --放分
- 请高手指教,怎样在DataGrid双击时,取得当前行的值,并显示在当前窗体上的TextBox控件中?谢谢.
- c# 串口通信serialport,循环发送问题,求大神赐教
- filestream.write问题
- 进来看看
http://www.vipcn.com/InfoView/Article_81027.html
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();
}}我也是找的人家的作者是王晓光
Time协议:这是以32位整数传递时间信息的一种协议。参见RFC0868。
Simple Network Time协议:这是一种更加精确的传递时间信息的协议。参见RFC1769。 你可以在http://rfc.linuxforum.net/找到相关RFC协议。