您的位置:首页 > 编程语言 > C语言/C++

windows环境C语言修改系统时间-WinAPI总结

2015-04-15 14:48 363 查看
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. TheSetSystemTime 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;
}


如有转载,请注明出处:http://blog.csdn.net/embedded_sky/article/details/45059323

作者:super_bert@csdn
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息