Linux当前时间

来源:互联网 发布:mac照片分类管理软件 编辑:程序博客网 时间:2024/05/16 14:48

1、获取当前时间

time_t t = time(NULL);struct tm *localt = localtime(&t); //本地时间struct tm *gm = gmtime(&t);        //UTC时间t = mktime(localt);                //转换成秒sprintf(timestr, "%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);

2、修改Ubuntu系统时区

# sudo tzconfig

选择 Asia
选择Shanghai

3、命令行设置时间

# sudo date -s ""   //来修改本地时间

格式:”2006-08-07 12:34:56”

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

#include <sys/time.h>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 */};

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

1 0