54 lines
1.1 KiB
C
54 lines
1.1 KiB
C
#include <stdlib.h>
|
|
#include <time.h>
|
|
#include <sys/time.h>
|
|
|
|
// 时间结构体
|
|
struct tm *local_time; // time to show or modify
|
|
|
|
void settime(int tm_hour, int tm_min, int tm_sec)
|
|
{
|
|
struct tm *time_set = NULL;
|
|
struct timeval tv;
|
|
struct timezone tz;
|
|
|
|
/* 获取当前时间 */
|
|
gettimeofday(&tv, &tz);
|
|
/* 获取当前时间 */
|
|
time_set = gmtime(&tv.tv_sec);
|
|
/* 设置当前时间结构体 */
|
|
time_set->tm_hour = tm_hour;
|
|
time_set->tm_min = tm_min;
|
|
time_set->tm_sec = tm_sec;
|
|
/* 获取用秒表示的时间 */
|
|
tv.tv_sec = mktime(time_set);
|
|
/* 设置当前时间 */
|
|
settimeofday(&tv, &tz);
|
|
}
|
|
|
|
void refresh_clock(void)
|
|
{
|
|
time_t timep;
|
|
|
|
time(&timep);
|
|
local_time = localtime(&timep); // 读取系统时间
|
|
|
|
// 时分秒
|
|
int hour = local_time->tm_hour;
|
|
int minute = local_time->tm_min;
|
|
int second = local_time->tm_sec;
|
|
printf("h = %d, m = %d, s = %d\n", hour, minute, second);
|
|
|
|
}
|
|
|
|
|
|
int main(int argc, char *argv[])
|
|
{
|
|
|
|
printf("修改前的时间:\n");
|
|
refresh_clock();
|
|
settime(11, 34, 50);
|
|
|
|
printf("修改后的时间:\n");
|
|
refresh_clock();
|
|
return 0;
|
|
} |