title: How to change system date in c#
body: <p>My program needs to be able to change the SystemDate on the machine.  After looking around I found this code and implemented it, however it does not seem to change the date at all.  The VM it is running on has time sync turned off, so I know the issue does not lie there.  Have I made a small mistake, or is there an easier way to change the system date?</p>
  
  <pre><code>[StructLayout(LayoutKind.Sequential)]
  private 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;
  }
  
  // Return Type: BOOL
  [System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint = "SetSystemTime")]
  [return:System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]
  private static extern bool SetSystemTime([InAttribute()] ref SYSTEMTIME lpSystemTime);
  
  
  
  public bool SetSystemDateTime(DateTime newDateTime)
  {
      bool result = false;
  
      try
      {
          newDateTime = newDateTime.ToUniversalTime();
  
          SYSTEMTIME sysTime = new SYSTEMTIME() 
              { wYear = (short)newDateTime.Year /* must be short */, 
              wMonth = (short)newDateTime.Month, 
              wDayOfWeek = (short)newDateTime.DayOfWeek, 
              wDay = (short)newDateTime.Day, 
              wHour = (short)newDateTime.Hour, 
              wMinute = (short)newDateTime.Minute, 
              wSecond = (short)newDateTime.Second, 
              wMilliseconds = (short)newDateTime.Millisecond };
  
          result = SetSystemTime(ref sysTime);
      }
      catch (Exception)
      {
          result = false;
      }
      return result;
  }
  </code></pre>