如何使用C#更改系统日期和时间?

如何使用C#更改系统日期和时间?

问题描述:

如何使用C#更改系统日期和时间?

我试过以下代码,但对我不适用..请帮助我





How To Change System Date and Time Using C#?
I have tried following code but didn't works for me..so kindly help me


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;
}

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

public void SetSystemDateTime(DateTime ServerDateTime)
{
       ServerDateTime = ServerDateTime.AddHours(-5).AddMinutes(-30);
       SYSTEMTIME st = new SYSTEMTIME();
       st.wYear = (short)ServerDateTime.Year; // must be short
st.wMonth = (short)ServerDateTime.Month;
       st.wDay = (short)ServerDateTime.Day;
       st.wHour = (short)ServerDateTime.Hour;
       st.wMinute = (short)ServerDateTime.Minute;
       st.wSecond = (short)ServerDateTime.Second;
       st.wMilliseconds = (short)ServerDateTime.Millisecond;
       SetSystemTime(ref st);
}

首先检查返回值:https://msdn.microsoft.com/en-us/library/windows/desktop/ms724942(v=vs.85 ).aspx [ ^ ] - 如果有问题,它将返回0.

然后您可以使用GetLastError来检索错误信息。



除非您有这些信息,否则您只是猜测问题可能是什么。
Start by checking the return value: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724942(v=vs.85).aspx[^] - if there is a problem, it will return 0.
You can then use GetLastError to retrieve the error information.

Until you have that info, you are just guessing what the problem might be.


请参阅 https://msdn.microsoft.com/en-us/library/windows/desktop/ms724942%28v=vs .85%29.aspx [ ^ ]。