最近在做到C#网络通信时,与原有C++开发的服务器通讯获取“客户端请求校时应答”消息包。即:客户端系统时间与服务器的同步时,即从服务器传过来的消息包解析后为time_t类型的。要更改客户端本地时间即将些time_t转换为.net 里的DateTime。下面即为转换的方法
Code
public DateTime Time_tToDateTime (long seconds)
{
double secs = Convert.ToDouble(seconds);
DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(secs);
//根据实际情况有可能不同。格林威治标准时间 与北京时间相差要晚8小时 如果出现此情况要加上8小时
//DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(secs)..AddHours(8);
return dt;
}
下面是如何进行更改客户端系统时间,调用API函数
先引用命名空间
using System.Runtime.InteropServices;
Code
#region 修改系统时间辅助方法
[DllImport("kernel32.dll")]
private static extern bool SetLocalTime(ref SYSTEMTIME time);
[StructLayout(LayoutKind.Sequential)]
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;
}
public static void 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;
SetLocalTime(ref st);
}
#endregion
在上面两个方法都处理完后,即可对系统时间进行更改。例如在按钮的单击事件中实现此功能即
Code
private void button1_Click(object sender, EventArgs e)
{
long tick = 1256265735;
double secs = Convert.ToDouble(tick);
SetDate(Time_tToDateTime(secs));
MessageBox.Show("修改成功!");
}