Change system date programmatically

Yoann. B picture Yoann. B · Mar 16, 2009 · Viewed 82.8k times · Source

How can I change the local system's date & time programmatically with C#?

Answer

Andrew Hare picture Andrew Hare · Mar 16, 2009

Here is where I found the answer.; I have reposted it here to improve clarity.

Define this structure:

[StructLayout(LayoutKind.Sequential)]
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;
}

Add the following extern method to your class:

[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetSystemTime(ref SYSTEMTIME st);

Then call the method with an instance of your struct like this:

SYSTEMTIME st = new SYSTEMTIME();
st.wYear = 2009; // must be short
st.wMonth = 1;
st.wDay = 1;
st.wHour = 0;
st.wMinute = 0;
st.wSecond = 0;

SetSystemTime(ref st); // invoke this method.