在C#中更改系统日期时间。在64位Windows Server 2008中,日期已更改,但时间未更改
我已使用以下程序更改系统日期时间在C#中更改系统日期时间。在64位Windows Server 2008中,日期已更改,但时间未更改,c#,windows,C#,Windows,我已使用以下程序更改系统日期时间 public struct SystemTime { public ushort Year; public ushort Month; public ushort DayOfWeek; public ushort Day; public ushort Hour; public ushort Minute; public ushort Second; public ushort Millisecond
public struct SystemTime
{
public ushort Year;
public ushort Month;
public ushort DayOfWeek;
public ushort Day;
public ushort Hour;
public ushort Minute;
public ushort Second;
public ushort Millisecond;
};
[DllImport("kernel32.dll", EntryPoint = "GetSystemTime", SetLastError = true)]
public extern static void Win32GetSystemTime(ref SystemTime sysTime);
[DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
public extern static bool Win32SetSystemTime(ref SystemTime sysTime);
private void button1_Click(object sender, EventArgs e)
{`enter code here`
// Set system date and time
SystemTime updatedTime = new SystemTime();
updatedTime.Year = (ushort)2009;
updatedTime.Month = (ushort)3;
updatedTime.Day = (ushort)16;
updatedTime.Hour = (ushort)10;
updatedTime.Minute = (ushort)0;
updatedTime.Second = (ushort)0;
// Call the unmanaged function that sets the new date and time instantly
Win32SetSystemTime(ref updatedTime);
}
系统日期已更改,但时间未更改。
我的任务是获取NTP服务器时间并更改截至NTP服务器时间的系统日期和时间。我获取NTP服务器日期和时间并更改日期,但我无法更改我的系统时间您正确声明了SetSystemTime(),但后来您忘了正确使用它。不能忽略返回值。修正:
if (!Win32SetSystemTime(ref updatedTime)) {
throw new System.ComponentModel.Win32Exception();
}
现在,您将从异常中发现失败的可能原因。有几种可能性,但我们可以猜测:更改时钟需要管理员权限,而您的程序不太可能拥有这些权限。您必须向用户请求权限才能执行此操作,方法是嵌入一个请求UAC提升的清单。演示如何做到这一点
以防您认为这是不合理的:请记住,更改时钟对运行程序非常有破坏性。在Windows中运行的许多基本服务都依赖于精确的时钟。它也不会持续很长时间,Windows会定期联系时间服务器重新校准时钟。你必须禁用它,请访问superuser.com。您将遇到的其他问题,如文件写入时间戳不正确、计划任务没有在应该运行的时候运行、web浏览器抱怨证书不正确、项目总是在重建,尽管您没有做任何更改,但这些都是您自己要处理的问题。不要这样做。对于与C#相关的编程问题,“讨论板”不是合适的标签。请使用实际适用于您所问问题的标签,以便对其进行适当分类以进行搜索,并引起可能帮助您获得答案的人的注意。不要无缘无故地随机抓取标签。谢谢。的可能副本没有同步到Windows内置的NTP服务器?在我的程序中它正在更改,但在系统中它没有显示。这里还有一个有趣的点是日期已更改,我可以在我的系统中看到。我在Windows server 2008中运行此操作。NTP服务器时间接收为UTC时间,因此我的系统采用UTC+5:30。如何将NTP服务器时间视为本地时间。