【问题标题】:How do I set the Windows system clock to the correct local time using C#?如何使用 C# 将 Windows 系统时钟设置为正确的本地时间?
【发布时间】:2011-08-30 07:18:48
【问题描述】:

如何使用 C# 将 Windows 系统时钟设置为正确的本地时间?

【问题讨论】:

  • 如何获得“正确的当地时间”?
  • “正确的当地时间”是什么意思?请解释一下。

标签: c# .net windows windows-xp clock


【解决方案1】:

要解决 SE_SYSTEMTIME_NAME 权限问题,请尝试创建一个计划任务来运行您的应用程序并启用“以最高权限运行”。

【讨论】:

    【解决方案2】:

    .NET 没有为此公开函数,但您可以使用 Win32 API SetSystemTime(在 kernel32.dll 中)方法。要获取 UTC 时间,您应该使用 NTP Protocol Client,然后根据您的区域设置将该时间调整为本地时间。

    public struct SYSTEMTIME
    {    
      public ushort wYear,wMonth,wDayOfWeek,wDay,wHour,wMinute,wSecond,wMilliseconds;
    }
    
    [DllImport("kernel32.dll")]
    public extern static uint SetSystemTime(ref SYSTEMTIME lpSystemTime);
    
    SYSTEMTIME systime = new SYSTEMTIME();
    systime = ... // Set the UTC time here
    SetSystemTime(ref systime);
    

    【讨论】:

    • 错了。这适用于 Windows Mobile 下的 Compact Framework。该问题被标记为“windows-xp”。
    【解决方案3】:

    您需要从 Windows API P/Invoke SetLocalTime function。在 C# 中这样声明:

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    internal static extern bool SetLocalTime(ref SYSTEMTIME lpSystemTime);
    
    [StructLayout(LayoutKind.Sequential)]
    internal struct SYSTEMTIME
    {
        public ushort wYear;
        public ushort wMonth;
        public ushort wDayOfWeek;    // ignored for the SetLocalTime function
        public ushort wDay;
        public ushort wHour;
        public ushort wMinute;
        public ushort wSecond;
        public ushort wMilliseconds;
    }
    

    要设置时间,您只需使用适当的值初始化SYSTEMTIME 结构的实例,然后调用该函数。示例代码:

    SYSTEMTIME time = new SYSTEMTIME();
    time.wDay = 1;
    time.wMonth = 5;
    time.wYear = 2011;
    time.wHour = 12;
    time.wMinute = 15;
    
    if (!SetLocalTime(ref time))
    {
        // The native function call failed, so throw an exception
        throw new Win32Exception(Marshal.GetLastWin32Error());
    }
    

    但是,请注意调用进程必须具有适当的权限才能调用此函数。在 Windows Vista 及更高版本中,这意味着您必须请求进程提升。


    或者,您可以使用SetSystemTime function,它允许您以UTC(协调世界时)设置时间。使用相同的SYSTEMTIME 结构,并且以相同的方式调用这两个函数。

    【讨论】:

      【解决方案4】:

      这里有几篇关于如何做到这一点的文章,其中包括查询原子钟的正确时间。

      http://www.codeproject.com/KB/IP/ntpclient.aspx

      http://www.codeproject.com/KB/datetime/SNTPClient.aspx

      【讨论】:

        猜你喜欢
        • 2023-04-03
        • 1970-01-01
        • 2010-11-28
        • 2017-05-27
        • 2011-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多