I already have this code that I got from: Change system date programmatically
I have a button that when I click the system time must be updated. But what is happening is that I don't get the result I want.
As you can see in the code below I set the Date and Time to April 25, 2018 1:00:00 AM but what I get is April 25, 2018 9:00:00 AM because of the added time by the UTC which is +8 in my time zone.
How can I set the system time directly to 1:00:00AM?
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEMTIME
{
public ushort wYear;
public ushort wMonth;
public ushort wDayOfWeek;
public ushort wDay;
public ushort wHour;
public ushort wMinute;
public ushort wSecond;
public ushort wMilliseconds;
}
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetSystemTime(ref SYSTEMTIME st);
private void UpdateSystemTime(DateTime dt)
{
SYSTEMTIME st = new SYSTEMTIME();
st.wYear = (ushort)dt.Year;
st.wMonth = (ushort)dt.Month;
st.wDay = (ushort)dt.Day;
st.wHour = (ushort)dt.Hour;
st.wMinute = (ushort)dt.Minute;
st.wSecond = (ushort)dt.Second;
SetSystemTime(ref st); // invoke this method.
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
timeToSet = new DateTime(year, month, day, hour, minute, second, second, DateTimeKind.Utc);
UpdateSystemTime(timeToSet);
}
See the documentation of SetSystemTime
:
Sets the current system time and date. The system time is expressed in Coordinated Universal Time (UTC).
This means that you'll have to pass the UTC, not the local time (or the time passed is interpreted as UTC).
When you created the DateTime
object, you passed DateTimeKind.Utc
, but this does not mean, that the values you pass are converted from local to UTC time, but rather the DateTime
object is created as a UTC time object. When you pass 1 AM as the hour, when you call dt.Hour
you will still get 1 AM, which is passed to SetSystemTime
and interpreted as 1 AM UTC, not 1 AM in local time.
You'll have to create a DateTime
for your local time, convert it to UTC and then pass the values to SetSystemTime
timeToSet = new DateTime(year, month, day, hour, minute, second, second, DateTimeKind.Local);
UpdateSystemTime(timeToSet.ToUniversalTime()); // this converts the local DateTime object to UTC