Windows Forms: How to change system date in C#

How to change system date in C# Windows Forms Application.

Drag and drop the DateTimePicker, Button from the Visual Studio toolbox into your form designer, then design a simple UI allows you to change the system date as shown below.

c# change system date time

Defining a struct datetime as shown below.

public struct SystemDate
    public ushort Year;
    public ushort Month;
    public ushort DayOfWeek;
    public ushort Day;
    public ushort Hour;
    public ushort Minute;
    public ushort Second;
    public ushort Millisecond;

How to change system date and time using c#

Next, We will use Win32 API to set the system date time.

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

Adding a click event handler to the Save button allows you to change the system date.

//c# set system time windows 10
private void btnSave_Click(object sender, EventArgs e)
    SystemDate systemDate = new SystemDate();
    systemDate.Month = (ushort)dateTimePicker.Value.Month;
    systemDate.Day = (ushort)dateTimePicker.Value.Day;
    systemDate.Year = (ushort)dateTimePicker.Value.Year;
    var result = SetSystemTime(ref systemDate);
    if (result)
        MessageBox.Show("You have successfully changed the system date.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);

If you want to change system date time in c#, you can modify your code as shown below.

DateTime date = new DateTime(2020, 13, 9, 11, 30, 15, 0, DateTimeKind.Utc);
SystemDate systime = new SystemDate(date);
SetSystemTime(ref systime);

and don't forget to add a constructor to your SystemDate struct.

public SystemDate(DateTime dt)
    Year = (ushort)dt.Year;
    Month = (ushort)dt.Month;
    DayOfWeek = (ushort)dt.DayOfWeek;
    Day = (ushort)dt.Day;
    Hour = (ushort)dt.Hour;
    Minute = (ushort)dt.Minute;
    Second = (ushort)dt.Second;
    Milliseconds = (ushort)dt.Millisecond;

You can also change the system date using the System.DateTime class along with System.Diagnostics.Process to execute the command for changing the system date.

// Get the desired date from the user input
DateTime newDate = dateTimePicker.Value;

// Format the date in a way that can be passed as an argument to the command prompt
string formattedDate = newDate.ToString("MM-dd-yyyy");

// Execute the command to change the system date
Process.Start("cmd.exe", $"/C date {formattedDate}");

Adding this code inside btnSave_Click. When the button is clicked, the btnSave_Click event handler is triggered.

Inside the event handler, it retrieves the selected date from the DateTimePicker, formats it to match the system date format, and then executes the command to change the system date using Process.Start() method with the command date.

Through this post you can easily set system date time in c#.