Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically set system time to the correct server time in .NET?

Is it possible to set the system time to the correct server time in .NET? I have a test case that mess up with the system time, I want to restore it in the test case's teardown. Is it possible to restore the correct time (e.g. from a server) programmatically?

NOTE: I will need this for both unit test and acceptance test. Injecting fake time does not apply for the latter.

like image 416
Louis Rhys Avatar asked Mar 07 '26 22:03

Louis Rhys


2 Answers

This is to set the time (once you know it):

Change system date programmatically

and if you mean to GET the time from a valid source, probably the answer in this discussion will help you: How to Query an NTP Server using C#?

like image 167
Jorge Alvarado Avatar answered Mar 10 '26 12:03

Jorge Alvarado


 void setDate(string dateInYourSystemFormat)
    {
        var proc = new System.Diagnostics.ProcessStartInfo();
        proc.UseShellExecute = true;
        proc.WorkingDirectory = @"C:\Windows\System32";
        proc.CreateNoWindow = true;
        proc.FileName = @"C:\Windows\System32\cmd.exe";
        proc.Verb = "runas";
        proc.Arguments = "/C date " + dateInYourSystemFormat;
        try
        {
            System.Diagnostics.Process.Start(proc);
        }
        catch
        {
            MessageBox.Show("Error to change time of your system");
            Application.ExitThread();
        }
    }
void setTime(string timeInYourSystemFormat)
    {
        var proc = new System.Diagnostics.ProcessStartInfo();
        proc.UseShellExecute = true;
        proc.WorkingDirectory = @"C:\Windows\System32";
        proc.CreateNoWindow = true;
        proc.FileName = @"C:\Windows\System32\cmd.exe";
        proc.Verb = "runas";
        proc.Arguments = "/C time " + timeInYourSystemFormat;
        try
        {
            System.Diagnostics.Process.Start(proc);
        }
        catch
        {
            MessageBox.Show("Error to change time of your system");
            Application.ExitThread();
        }
    }
like image 35
Hiren Raiyani Avatar answered Mar 10 '26 10:03

Hiren Raiyani