一尘不染

以编程方式更改系统日期

c#

如何使用C#以编程方式更改本地系统的日期和时间?


阅读 235

收藏
2020-05-19

共1个答案

一尘不染

这是我找到答案的地方。;
我将其重新张贴在此处以提高清晰度。

定义此结构:

[StructLayout(LayoutKind.Sequential)]
public struct SYSTEMTIME
{
    public short wYear;
    public short wMonth;
    public short wDayOfWeek;
    public short wDay;
    public short wHour;
    public short wMinute;
    public short wSecond;
    public short wMilliseconds;
}

将以下extern方法添加到您的类中:

[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetSystemTime(ref SYSTEMTIME st);

然后使用如下结构实例调用该方法:

SYSTEMTIME st = new SYSTEMTIME();
st.wYear = 2009; // must be short
st.wMonth = 1;
st.wDay = 1;
st.wHour = 0;
st.wMinute = 0;
st.wSecond = 0;

SetSystemTime(ref st); // invoke this method.
2020-05-19