C#通过Win32API设置客户端系统时间的方法详解

  public class SysTimeHelper

  {

  [DllImport("kernel32.dll")]

  public static extern bool SetSystemTime(ref SystemTime st);

  [DllImport("Kernel32.dll")]

  public static extern bool SetLocalTime(ref SystemTime st);

  [DllImport("Kernel32.dll")]

  public static extern void GetSystemTime(ref SystemTime st);

  [DllImport("Kernel32.dll")]

  public static extern void GetLocalTime(ref SystemTime st);

  public static string GetLocalTime()

  {

  SystemTime st = new SystemTime();

  GetLocalTime(ref st);

  return st.ToString();

  }

  public static bool SetLocalTimeByStr(string timestr)

  {

  bool flag = false;

  SystemTime sysTime = new SystemTime();

  DateTime dt = Convert.ToDateTime(timestr);

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

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

  sysTime.wDay = Convert.ToUInt16(dt.Day);

  sysTime.wHour = Convert.ToUInt16(dt.Hour);

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

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

  try

  {

  flag = SetLocalTime(ref sysTime);

  }

  catch (Exception ex)

  {

  string e = ex.Message;

  return false;

  }

  return flag;

  }

  ///

  /// 时间戳转为C#格式时间

  ///

  ///

  ///

  public static DateTime ConvertStringToDateTime(string timeStamp)

  {

  DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));

  long lTime = long.Parse(timeStamp + "0000");

  TimeSpan toNow = new TimeSpan(lTime);

  return dtStart.Add(toNow);

  }

  ///

  /// 时间戳转为C#格式时间10位

  ///

  /// Unix时间戳格式

  /// C#格式时间

  public static DateTime GetDateTimeFrom1970Ticks(long curSeconds)

  {

  DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));

  return dtStart.AddSeconds(curSeconds);

  }

  }