1. 声明代码
//imports SetLocalTime function from kernel32.dll [DllImport("coredll.dll", SetLastError = true)] public static extern int SetLocalTime(ref SystemTime lpSystemTime); //struct for date/time apis 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; }
2. 调用代码示例:
try { // 通过WebService获取服务器时间 SCM.SOAPService soap = new SCM.SOAPService(); DateTime remoteTime = soap.getSystemTime(); // 给结构体赋值 SystemTime newTime = new SystemTime(); newTime.wYear = (short)remoteTime.Year; newTime.wMonth = (short)remoteTime.Month; newTime.wDay = (short)remoteTime.Day; newTime.wHour = (short)remoteTime.Hour; newTime.wMinute = (short)remoteTime.Minute; newTime.wSecond = (short)remoteTime.Second; newTime.wMilliseconds = (short)remoteTime.Millisecond; newTime.wDayOfWeek = (short)remoteTime.DayOfWeek; // 设置本地时间 SetLocalTime(ref newTime); } catch { MessageBox.Show("获取服务器时间设置本地时间失败!", "错误提示",MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1); }