I have this code to change system time.
This code works but somehow doesn’t accept local system Time Zone.
It seems that I have to add some more methods to do it or ??
How it could be???
Any clue?
public static class SystemFunctions
{
public struct SystemTime
{
public ushort Year;
public ushort Month;
public ushort DayOfWeek;
public ushort Day;
public ushort Hour;
public ushort Minute;
public ushort Second;
public ushort Millisecond;
};
[DllImport("kernel32.dll", EntryPoint = "GetSystemTime", SetLastError = true)]
public extern static void Win32GetSystemTime(ref SystemTime sysTime);
[DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
[return: System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]
public extern static bool Win32SetSystemTime(ref SystemTime sysTime);
public static bool SetSystemTime(DateTime dateTime)
{
SystemTime updatedTime = new SystemTime();
updatedTime.Year = (ushort)dateTime.Year;
updatedTime.Month = (ushort)dateTime.Month;
updatedTime.Day = (ushort)dateTime.Day;
// UTC time; it will be modified according to the regional settings of the target computer so the actual hour might differ
updatedTime.Hour = (ushort)dateTime.Hour;
updatedTime.Minute = (ushort)dateTime.Minute;
updatedTime.Second = (ushort)dateTime.Second;
// Call the unmanaged function that sets the new date and time instantly
return Win32SetSystemTime(ref updatedTime);
}
}
UPDATES
So the final solution was to convert local time to ToUniversalTime and just apply it.
But before we have to apply correct time zone as well.
SetSystemTime accepts only UTC time. So you need to do conversion from local to UTC in your C# code if needed.