SetSystemTime
The SetSystemTime function is provided by the Windows API and allows the system clock time to be modified. You can call the function using Platform Invocation Services (P/Invoke) from within C# source code to set the time using Co-ordinated Universal Time (UTC). When viewed, the time is offset using the operating system settings to show the user's equivalent local time.
As the function requires the use of P/Invoke, you should add the following using directive. This will simplify the code that accesses items from the System.Runtime.InteropServices namespace:
using System.Runtime.InteropServices;
The function that we will be using accepts a UTC date and time using the SYSTEMTIME structure. The structure consists of eight integer values that correspond to the various parts of the date, from the year to the millisecond. To declare the new type, add the following code:
[StructLayout(LayoutKind.Sequential)]
public 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;
}
We can now declare the SetSystemTime function, using the new structure as the only parameter:
[DllImport("kernel32.dll")]
public extern static uint SetSystemTime(ref SYSTEMTIME lpSystemTime);
To set the system time, you simply initialise a SYSTEMTIME value and call the function, passing the value by reference. You may set the values for all parts of the date and time. Any elements that you omit will default to zero. The following code, therefore, sets the date to 7 August 2010 and the time to 12:30. The seconds and milliseconds are set to zero. Remember that this time is expressed as UTC so if the user's time zone includes a UTC offset that is not zero, the time will not appear as 12:30.
SYSTEMTIME time = new SYSTEMTIME();
time.Day = 7;
time.Month = 8;
time.Year = 2010;
time.Hour = 12;
time.Minute = 30;
SetSystemTime(ref time);
NB: Some systems may be configured to automatically set the time using information from the Internet or from a network server. In these cases the time may not change or may quickly be reset. If the update fails, the function returns zero.
7 August 2010