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

MS Windows 专栏收录该内容
11 篇文章 0 订阅

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;
}


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

作者:super_bert@csdn


  • 1
    点赞
  • 0
    评论
  • 3
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值