日期:2014-05-18  浏览次数:20899 次

如何通过C#修改计算机系统时间?急急!
获取数据库时间,根据数据库时间来修改计算机系统的时间!



------解决方案--------------------
#region ComputerTime
[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 class Win32
{
[DllImport( "Kernel32.dll ")]
public static extern bool SetSystemTime(ref SystemTime SysTime);
[DllImport( "Kernel32.dll ")]
public static extern void GetSystemTime(ref SystemTime SysTime);
}
#endregion

#region 时间同步
/// <summary>
/// 设置与服务器同步时间
/// </summary>
public void SynchronousTime()
{
try
{
#region 更改计算机时间

SystemTime sysTime = new SystemTime();

DateTime ServerTime = 需要更改的时间

sysTime.wYear = Convert.ToUInt16(ServerTime.Year);

sysTime.wMonth = Convert.ToUInt16(ServerTime.Month);

//处置北京时间

int nBeijingHour = ServerTime.Hour - 8;

if (nBeijingHour <= 0)
{
nBeijingHour += 24;

sysTime.wDay = Convert.ToUInt16(ServerTime.Day - 1);

sysTime.wDayOfWeek = Convert.ToUInt16(ServerTime.DayOfWeek - 1);
}
else
{
sysTime.wDay = Convert.ToUInt16(ServerTime.Day);

sysTime.wDayOfWeek = Convert.ToUInt16(ServerTime.DayOfWeek);
}

sysTime.wHour = Convert.ToUInt16(nBeijingHour);

sysTime.wMinute = Convert.ToUInt16(ServerTime.Minute);

sysTime.wSecond = Convert.ToUInt16(ServerTime.Second);

sysTime.wMiliseconds = Convert.ToUInt16(ServerTime.Millisecond);

Win32.SetSystemTime(ref sysTime);

#endregion
}
catch
{
//产生错误则不引发异常。
}
}
#endregion

==========
晕死了