【发布时间】:2023-09-28 19:56:01
【问题描述】:
您好,我知道之前有人问过这个问题,但我需要帮助更改 c# 中的系统日期时间。在进行谷歌搜索时,我发现了一个建议以下代码的网站
public struct SYSTEMTIME
{
public ushort wYear,wMonth,wDayOfWeek,wDay, wHour,wMinute,wSecond,wMilliseconds;
}
[DllImport("kernel32.dll")]
public extern static void GetSystemTime(ref SYSTEMTIME lpSystemTime);
/// <param name="lpSystemTime">[in] Pointer to a SYSTEMTIME structure that
/// contains the current system date and time.</param>
[DllImport("kernel32.dll")]
public extern static uint SetSystemTime(ref SYSTEMTIME lpSystemTime);
static void Main()
{
Console.WriteLine(DateTime.Now.ToString());
SYSTEMTIME st = new SYSTEMTIME();
GetSystemTime(ref st);
Console.WriteLine("Adding 1 hour...");
st.wHour = (ushort)(st.wHour + 1 % 24);
if (SetSystemTime(ref st) == 0)
Console.WriteLine("FAILURE: SetSystemTime failed");
Console.WriteLine(DateTime.Now.ToString());
Console.WriteLine("Setting time back...");
st.wHour = (ushort)(st.wHour - 1 % 24);
SetSystemTime(ref st);
Console.WriteLine(DateTime.Now.ToString());
Console.WriteLine("Press Enter to exit");
Console.Read();
}
但是当我在我的系统中运行它时,它显示当前日期/时间没有变化。我应该进行任何更改吗?
编辑:收到消息 FAILURE: SetSystemTime failed when I try to run
【问题讨论】:
-
这是例如测试目的?在这种情况下,最好将时钟抽象出来(因此,删除对
DateTime.Now的任何直接调用)而不是摆弄系统的实际时间。 -
此代码更改日期并恢复它。除非您将“FAILURE:SetSystemTime failed”发送到控制台 - 时间已成功更改.. 但是几毫秒.. 删除“时间恢复部分”,并根据您的需要调整代码。
-
@Damien_The_Unbeliever 实际上有一个程序应该为用户指定的特定年份生成数据。认为只要用户想要该特定年份的消息,就可以更改系统日期时间
-
您想在哪个版本的 Windows 上运行此代码?因为我认为用户不是管理员组的一部分,所以它可能不起作用。
-
@BlackFrog 主要用于测试真正...在 windows xp 中