Click here to Skip to main content
15,890,609 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How To Change System Date and Time Using C#?
I have tried following code but didn't works for me..so kindly help me


C#
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);
}
Posted
Updated 23-Sep-19 22:27pm
Comments
Philippe Mori 9-Apr-15 21:14pm    
As far as I know, system time cannot be changed without running the application as an administrator.

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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900