嗨,我知道这已被问过,但我需要帮助在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();
}
但是,当我在我的系统上运行它,它显示了当前的日期/时间没有变化。我应该做出改变吗?
编辑:得到的消息失败:SetSystemTime失败,当我尝试运行
这是例如测试目的?在这种情况下,抽象出时钟通常会更好(因此,除去直接调用'DateTime.Now')而不是摆弄系统的实际时间。 –
此代码更改日期并将其还原。除非你将“FAILURE:SetSystemTime failed”设置为控制台 - 时间已成功更改..但是一些毫秒。删除“time-reverting part”,并根据需要调整代码。 – rufanov
@Damien_The_Unbeliever实际上有一个应该生成用户指定的特定年份的数据的程序。认为只要用户想要特定年份的消息,就可以改变系统的日期时间 – Drake