3

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.

Louis Rhys
  • 34,517
  • 56
  • 153
  • 221
  • 2
    A cleaner way of dealing with time in unit tests is talked about here: http://ayende.com/blog/3408/dealing-with-time-in-tests – ilivewithian Nov 29 '12 at 10:40
  • 1
    It is probably easier and safer to abstract the concept of time in your code and then use a stub in your unit test to provide whatever time you require. E.g. `interface ITimeSource { DateTime Now { get; } }`. – Martin Liversage Nov 29 '12 at 10:45
  • @MartinLiversage I will need to do acceptance test as well, I will still have to manipulate the system time. – Louis Rhys Nov 29 '12 at 10:51

2 Answers2

4

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#?

Community
  • 1
  • 1
Jorge Alvarado
  • 2,664
  • 22
  • 33
2
 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();
        }
    }
Hiren Raiyani
  • 754
  • 2
  • 12
  • 28