【问题标题】:Programmatically set system time to the correct server time in .NET?以编程方式将系统时间设置为 .NET 中的正确服务器时间?
【发布时间】:2012-11-17 09:54:18
【问题描述】:

是否可以在 .NET 中将系统时间设置为正确的服务器时间?我有一个弄乱系统时间的测试用例,我想在测试用例的拆解中恢复它。 是否可以通过编程方式恢复正确的时间(例如从服务器)?

注意:单元测试和验收测试都需要这个。注入假时间不适用于后者。

【问题讨论】:

  • 这里讨论了一种在单元测试中处理时间的更简洁的方法:ayende.com/blog/3408/dealing-with-time-in-tests
  • 在你的代码中抽象时间的概念,然后在你的单元测试中使用一个存根来提供你需要的任何时间,这可能更容易和更安全。例如。 interface ITimeSource { DateTime Now { get; } }.
  • @MartinLiversage 我还需要做验收测试,我仍然需要操纵系统时间。

标签: c# .net unit-testing datetime testing


【解决方案1】:

这是设置时间(一旦你知道了):

Change system date programmatically

如果您打算从有效来源获取时间,那么本讨论中的答案可能会对您有所帮助: How to Query an NTP Server using C#?

【讨论】:

    【解决方案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();
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2018-05-06
      • 1970-01-01
      • 1970-01-01
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 2011-07-30
      • 2016-08-24
      • 1970-01-01
      相关资源
      最近更新 更多