Linux系统设置系统时间有两种方法:
1.使用命令date
2.使用系统调用settimeofday,gettimeofday
注意:不管使用上面哪一种方法都必须是root权限。
如果系统连接上了网络,设置的时间和网络时间不同,系统会自动使用网络中的时间。
1.使用命令date
在命令行中可以使用:
sudo date --s "2020-6-30 10:10:10"
2.使用系统调用settimeofday
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
static void time_set(int year,int month,int day,int hour,int min,int sec)
{
struct tm tptr;
struct timeval tv;
tptr.tm_year = year - 1900;
tptr.tm_mon = month - 1;
tptr.tm_mday = day;
tptr.tm_hour = hour;
tptr.tm_min = min;
tptr.tm_sec = sec;
tv.tv_sec = mktime(&tptr);
tv.tv_usec = 0;
settimeofday(&tv, NULL);
system(sudo hwclock -w);//将设置好的系统时间写入到rtc中
}
C语言settimeofday()函数:设置当前时间戳
头文件:
1 | #include <sys/time.h> #include <unistd.h> |
定义函数:
1 | int settimeofday(const struct timeval *tv, const struct timezone *tz); |
函数说明:
settimeofday()会把目前时间设成由tv 所指的结构信息,当地时区信息则设成tz 所指的结构。详细的说明请参考gettimeofday()。
注意,在Linux下,只有root 权限才能使用此函数修改时间。
返回值:成功则返回0,失败返回-1,错误代码存于errno。
错误代码:
EPERM 并非由root 权限调用settimeofday(),权限不够。
EINVAL 时区或某个数据是不正确的,无法正确设置时间。
C语言gettimeofday()函数:获取当前时间
头文件:
1 | #include <sys/time.h> #include <unistd.h> |
定义函数:int gettimeofday (struct timeval * tv, struct timezone * tz);
函数说明:gettimeofday()会把目前的时间有tv 所指的结构返回,当地时区的信息则放到tz 所指的结构中。
timeval 结构定义为:
1 2 3 4 | struct timeval{ long tv_sec; //秒 long tv_usec; //微秒 }; |
timezone 结构定义为:
1 2 3 4 5 | struct timezone { int tz_minuteswest; //和Greenwich 时间差了多少分钟 int tz_dsttime; //日光节约时间的状态 }; |
上述两个结构都定义在/usr/include/sys/time.h. tz_dsttime 所代表的状态如下
1 2 3 4 5 6 7 8 9 10 11 | DST_NONE //不使用 DST_USA //美国 DST_AUST //澳洲 DST_WET //西欧 DST_MET //中欧 DST_EET //东欧 DST_CAN //加拿大 DST_GB //大不列颠 DST_RUM //罗马尼亚 DST_TUR //土耳其 DST_AUSTALT //澳洲(1986 年以后) |
返回值:成功则返回0,失败返回-1,错误代码存于errno。
附加说明:EFAULT 指针tv 和tz 所指的内存空间超出存取权限。