Setting the system time

by Kent Reisdorph

Some applications expect the system time to be synchronized with a known time source. Other applications depend on several machines on a network to have the same date and time. You can set the system time for a particular machine by calling the SetLocalTime() or SetSystemTime() functions. These functions operate in the same way except that the specified time is local time for the SetLocalTime() function and UTC time for the SetSystemTime() function. These functions are used to set both the date and the time, despite what their names would indicate. This article will focus on the SetLocalTime() function.

Before calling SetLocalTime() you must declare an instance of the SYSTEMTIME structure and initialize it’s members to the new date and time. SYSTEMTIME is declared as follows:

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

As you can see, this structure’s members correspond to the separate parts of dates and times. The dwDayOfWeek member is not used when setting the system date and time (it is, however, used when retrieving the date and time using the GetLocalTime() and GetSystemTime() functions).

After you have set the members of this structure you call SetLocalTime() to update the system date and time. Here is the declaration for SetLocalTime(): 

BOOL SetLocalTime(
  CONST SYSTEMTIME *lpSystemTime);

SetLocalTime() returns a non-zero value if the call succeeded, or zero if the call failed. Call GetLastError() to determine the cause of the failure if zero is returned. Reasons for failure could include a bad value (specifying a minute value greater than 59 for example) or because the user didn’t have proper access to change the system time.

The following code adds one minute to the current time. It first declares an instance of TDateTime to get the current date and time. It then decodes the date and time in order to get the individual date and time values. These values are then assigned to their corresponding member in the SYSTEMTIME structure (with the exception that the minute is incremented by one). Here is the example code: 

unsigned short year, month, day;
unsigned short h, m, s, ms;
TDateTime dt = Now();
dt.DecodeDate(&year, &month, &day);
dt.DecodeTime(&h, &m, &s, &ms);
SYSTEMTIME st;
st.wYear = year;
st.wMonth = month;
st.wDay = day;
st.wHour = h;
st.wMinute = m + 1;
st.wSecond = s;
st.wMilliseconds = ms;
SetLocalTime(&st);

 Note that this code doesn’t take into account the fact that the current minute may be 59. In that case both the hour and the minute values should be changed accordingly. Obviously, many values would have to be manually adjusted if the current date and time were December 31, 2001 at 23:59:00.

Changing the system time is easy but care must be taken to use proper values if you are simply making a time adjustment.