Linux时间

1、获取当前时间

//本地时间
char buf[100] = {0};
time_t t = time(NULL);
struct tm *localt = localtime(&t);

sprintf(buf, "%4d-%02d-%02d-%02d:%02d:%02d", localt->tm_year + 1900, localt->tm_mon + 1, 
localt->tm_mday, localt->tm_hour, localt->tm_min, localt->tm_sec);
printf("localtime: %s\n", buf);

# ./a.out 
localtime: 2017-05-12-12:45:26
//UTC
char buf[100] = {0};
time_t t = time(NULL);

struct tm *gm = gmtime(&t);

sprintf(buf, "%4d-%02d-%02d-%02d:%02d:%02d", gm->tm_year + 1900, gm->tm_mon + 1, 
gm->tm_mday, gm->tm_hour, gm->tm_min, gm->tm_sec);
printf("gmtime: %s\n", buf);

# ./a.out 
gmtime: 2017-05-12-04:45:26
//格式化时间
char buf[100] = {0};
time_t the_time;  
struct tm *tm_ptr;  

(void)time(&the_time);  
tm_ptr = localtime(&the_time);  
strftime(buf, sizeof(buf), "%a %d %B %I:%M:%S %p", tm_ptr);  

printf("strftime: %s\n", buf);  

# ./a.out 
strftime: Fri 12 May 01:23:14 PM
//格式化时间
char buf[100] = {0};
time_t the_time;  
struct tm *tm_ptr;  

(void)time(&the_time);  
tm_ptr = localtime(&the_time);  
strftime(buf, sizeof(buf), "%c", tm_ptr);

printf("strftime: %s\n", buf);  

# ./a.out 
strftime: Fri May 12 13:31:58 2017

c:日期
x:年月日(05/12/17)
X:时分秒(14:00:34)
Y:年份
y:年份后两位(00-99)
a:星期简写
A:星期全称
w:7进制星期(0-6,0代表星期天)
u:7进制星期(1-7,1代表星期一)
U:年份中星期(星期天是一周的第一天)
V:年份中星期(星期一是一周的第一天)
b:月份简写
B:月份全称
m:12进制月份(01-12)
d:月份中的日(1-31)
j:年份中的日(001-366)
H:24进制小时(0-23)
I:12进制小时(01-12)
p:大写上午或下午
P:小写上午或下午
S:秒
Z:地理时区

//转换成秒
time_t t = time(NULL);
struct tm *localt = localtime(&t);
t = mktime(localt);
printf("mktime: %d\n", t);

# ./a.out 
mktime: 1494535526

2、修改Ubuntu系统时区

# sudo tzconfig

选择Asia
选择Shanghai

3、命令修改时间

# sudo date -s ""	//系统时钟(kernel)

参考格式:
"2006-08-07 12:34:56"
"20060807 12:34:56"

# hwclock --set --date "" //硬件时钟

参考格式:"06/08/07 12:34:56"

-r:查看硬件时钟
-w:系统时钟同步到硬件时钟

4、函数设置时间
stime这个函数只能精确到秒
int stime(time_t *t);
t是以秒为单位的时间值,从GMT1970年1月1日0时0分0秒开始计算
settimeofday精确到微妙

int gettimeofday(struct timeval *tv, struct timezone *tz);
int settimeofday(const struct timeval *tv, const struct timezone *tz);

struct timezone 
{
    int tz_minuteswest;     /* minutes west of Greenwich */
    int tz_dsttime;         /* type of DST correction */
};

tz参数为时区,时区结构中tz_dsttime在linux中不支持,应该置为0,通常将参数tz设置为NULL,表示使用当前系统的时区设置CMOS时间
其实它是通过RTC(Real-time clock)设备驱动来完成的,你可以用ioctl()函数来设置时间,当然也可以通过操作/dev/rtc设备文件

原文地址:https://www.cnblogs.com/zhangxuechao/p/11709980.html