Question

I have the following C# code:

 public static void SetDateTime(System.DateTime datetime)
    {
        var systemNew = new SystemTime
            {
                wDay = (ushort)datetime.Day,
                wMonth = (ushort)datetime.Month,
                wYear = (ushort)datetime.Year,
                wHour = (ushort)datetime.Hour,
                wMinute = (ushort)datetime.Minute,
                wSecond = (ushort)datetime.Second,
                wMilliseconds = (ushort)datetime.Millisecond
            };

        // update system clock
        NativeMethods.SetLocalTime(ref systemNew);
        int errorCode = Marshal.GetLastWin32Error();
        if (errorCode != 0)
        {
            Debug.WriteLine("SetDateTime error: {0}", errorCode);
        }
    }

internal struct SystemTime
{
    internal ushort wDay;
    internal ushort wDayOfWeek;
    internal ushort wHour;
    internal ushort wMilliseconds;
    internal ushort wMinute;
    internal ushort wMonth;
    internal ushort wSecond;
    internal ushort wYear;
}

internal static class NativeMethods
{
    [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    internal static extern int SetLocalTime(ref SystemTime lpSystemTime);
}

However, this gives me errorcode 87 everytime I call the method, any ideas?

Edit: I checked it on my local machine and it works fine there. It doesn't work with Remote Debugging from Visual Studio, even though the remote process runs under the same account as my local account and it's an administrator on that system.

Was it helpful?

Solution

The code which you posted don't contain any value of datetime which you used to reproduce the error.

For example DateTime.Year property can have the value between 1 and 9999 (see here). On the other side the wYear field of SYSTEMTIME can be between 1601 and 30827.

So I recommend you first of all to verify old values of input struct which you use as the input to SetLocalTime.

UPDATED: It seems to me that I know the origin of the problem now. You defined SystemTime with the wrong order of fields as:

internal struct SystemTime
{
    internal ushort wDay;
    internal ushort wDayOfWeek;
    internal ushort wHour;
    internal ushort wMilliseconds;
    internal ushort wMinute;
    internal ushort wMonth;
    internal ushort wSecond;
    internal ushort wYear;
}

but SYSTEMTIME is defined as

typedef struct _SYSTEMTIME {
  WORD wYear;
  WORD wMonth;
  WORD wDayOfWeek;
  WORD wDay;
  WORD wHour;
  WORD wMinute;
  WORD wSecond;
  WORD wMilliseconds;
} SYSTEMTIME, *PSYSTEMTIME;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top