1.MSDN上有关时间设置API的详细介绍
①SYSTEMTIME结构体
typedef struct _SYSTEMTIME {
WORD wYear; /*年*/
WORD wMonth; /*月*/
WORD wDayOfWeek; /*星期 0-6 0-Sunday...*/
WORD wDay; /*日*/
WORD wHour; /*时*/
WORD wMinute; /*分*/
WORD wSecond; /*秒*/
WORD wMilliseconds; /*微妙*/
} SYSTEMTIME, *PSYSTEMTIME;
②GetLocalTime获取本地时间(北京时间)
void WINAPI GetLocalTime(
_Out_ LPSYSTEMTIME lpSystemTime
);
③SetLocalTime设置本地时间(北京时间),
BOOL WINAPI SetLocalTime(
_In_ const SYSTEMTIME *lpSystemTime
);
The calling process must have the SE_SYSTEMTIME_NAME privilege. This privilege is disabled by default. TheSetLocalTime function enables the SE_SYSTEMTIME_NAME privilege before changing the local time and disables the privilege before returning. For more information, see Running with Special Privileges.
MSDN的说明,进程必须有SE_SYSTEMTIME_NAME的权限残能成功设置本地时间,就好比只有Administrator才能修改windows时间。
④GetSystemTime获取系统时间(格林威治时间,北京时间-8H)
void WINAPI GetSystemTime(
_Out_ LPSYSTEMTIME lpSystemTime
);
⑤SetSystemTime设置系统时间(格林威治时间,北京时间-8H)
BOOL WINAPI SetSystemTime(
_In_ const SYSTEMTIME *lpSystemTime
);The calling process must have the SE_SYSTEMTIME_NAME privilege. This privilege is disabled by default. The
SetSystemTime function enables the SE_SYSTEMTIME_NAME privilege before changing the system time and disables the privilege before returning. For more information, see Running with Special Privileges.
同样,系统时间也要有SE_SYSTEMTIME_NAME权限才能修改。
2.一个传入年月日时分秒字符串修改系统时间的demo
/*
* @function : 设置Windows本地时间
* @author : super_bert
* @in : time_string - 14字节时间字符串(such as 20150415093000)
* @return : 0 - success
* -1 - failure
**/
int set_local_time(const char *time_string)
{
SYSTEMTIME system_time = {0};
char year[4 + 1] = {0};
char month[2 + 1] = {0};
char day[2 + 1] = {0};
char hour[2 + 1] = {0};
char minute[2 + 1] = {0};
char second[2 + 1] = {0};
int index = 0;
strncpy(year, time_string + index, 4);
index += 4;
strncpy(month, time_string + index, 2);
index += 2;
strncpy(day, time_string + index, 2);
index += 2;
strncpy(hour, time_string + index, 2);
index += 2;
strncpy(minute, time_string + index, 2);
index += 2;
strncpy(second, time_string + index, 2);
index += 2;
GetLocalTime(&system_time);
system_time.wYear = atoi(year);
system_time.wMonth = atoi(month);
system_time.wDay = atoi(day);
system_time.wHour = atoi(hour);
system_time.wMinute = atoi(minute);
system_time.wSecond = atoi(second);
if (0 == SetLocalTime(&system_time))
{
return -1;
}
return 0;
}
作者:super_bert@csdn