2

I use SYSTEMTIME struct to change my system datetime like follows:

 [DllImport("kernel32.dll")]
 public extern static uint SetSystemTime(ref SYSTEMTIME lpSystemTime);

 private void button1_Click(object sender, EventArgs e)
 {
     SYSTEMTIME st = new SYSTEMTIME();
     st.wYear = 2009;
     st.wMonth = 1;
     st.wDay = 1;
     st.wHour = 23;
     st.wMinute = 1;
     st.wSecond = 1;
     SetSystemTime(ref st);
 }

the Date was changed, but the Time is not effected I want to change my system date and time in 24 mode. can you help me about that ?

Abdullah Zaid
  • 171
  • 3
  • 9

2 Answers2

1

I can't reproduce this. With a very simple console application below, I can either get it to do nothing at all (running normally, with no elevated privileges) or I can change both date and time (running it as an administrator). It never changed just the date. However, that's on Windows 7, with UAC enabled. Perhaps you're running on a different version, or with different access controls? I strongly suspect this is an access control issue.

using System;
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential)]
struct SYSTEMTIME
{
    [MarshalAs(UnmanagedType.U2)] public short Year;
    [MarshalAs(UnmanagedType.U2)] public short Month;
    [MarshalAs(UnmanagedType.U2)] public short DayOfWeek;
    [MarshalAs(UnmanagedType.U2)] public short Day;
    [MarshalAs(UnmanagedType.U2)] public short Hour;
    [MarshalAs(UnmanagedType.U2)] public short Minute;
    [MarshalAs(UnmanagedType.U2)] public short Second;
    [MarshalAs(UnmanagedType.U2)] public short Milliseconds;
}

class Test
{
    [DllImport("kernel32.dll")]
    public extern static uint SetSystemTime(ref SYSTEMTIME lpSystemTime);

    static void Main()
    {
        SYSTEMTIME st = new SYSTEMTIME();
        st.Year = 2009;
        st.Month = 1;
        st.Day = 1;
        st.Hour = 23;
        st.Minute = 1;
        st.Second = 1;
        SetSystemTime(ref st);
   } 
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

SYSTEMTIME should look like this:

typedef struct _SYSTEMTIME {
  WORD wYear;
  WORD wMonth;
  WORD wDayOfWeek;
  WORD wDay;
  WORD wHour;
  WORD wMinute;
  WORD wSecond;
  WORD wMilliseconds;
} SYSTEMTIME, *PSYSTEMTIME;

SetSystemTime() should return true on success.

And time is set in 24hr format.

wYear: 1601-30827

wMonth: 1-12

wDayOfWeek: 0-6

wDay: 1-31

wHour: 0-23

wMinute: 0-59

wSecond: 0-59

wMilliseconds: 0-999

Danpe
  • 18,668
  • 21
  • 96
  • 131