Linux中c/c++获取时间

1.纳秒级时间精度

纳秒级时间精度timespecint clock_gettime(clockid_t, struct timespec *)配合使用,其中:
第一个参数clockid_t,时钟类型:
CLOCK_REALTIME 统当前时间,从1970年1.1日算起
CLOCK_MONOTONIC 系统的启动时间,不能被设置(和单片机启动后开始计时类似)
CLOCK_PROCESS_CPUTIME_ID 本进程运行时间
CLOCK_THREAD_CPUTIME_ID 本线程运行时间
第二个参数获取的时间:

struct timespec {
time_t tv_sec; // seconds 
long tv_nsec; // and nanoseconds 
};

其中,tv_sec当前时刻的秒数,tv_nsec当前时刻的纳秒数(表示秒数的小数点后的数字)。

2.微妙级时间精度

微妙级时间精度, timevalint gettimeofday(struct timeval *tv, struct timezone *tz)配合使用,获得当前精确时间(1970年1月1日到现在的时间),其中:
第一个参数获取的时间:

struct timeval {
time_t tv_sec; // seconds 
long tv_usec; // microseconds 
};

其中,tv_sec当前时刻的秒数,tv_nsec当前时刻的微秒数(表示秒数的小数点后的数字)。
第二个参数为时区信息:

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

返回系统设置的所在的时区的信息。
该函数和clock_gettime()CLOCK_REALTIME效果相似

3.秒级精度

秒级精度,time_ttime(time_t *t)配合使用,获取从1970年1.1日算到现在的秒数。

4.将至今的秒数换算成日期和时间

将至今的秒数换算成日期和时间
使用struct tm* localtime_r( const time_t* timer, struct tm* result );//线程安全
其中:第一个参数为time_t为至今的秒数,可以由以上三种方式得到
第二个参数为转化后的年月日时分秒等信息结构体:

struct tm {
    int tm_sec; //seconds after the minute[0-60]
    int tm_min; //minutes after the hour[0-59]
    int tm_hour; //hours since midnight[0-23]
    int tm_mday; //day of the month[0-31]
    int tm_mon; //months since January[0-11]
    int tm_year; //years since 1900
    int tm_wday; //days since Sunday[0-6]
    int tm_yday; //days since January
    int tm_isdst; //Daylight Savings Time flag
    int tm_gmtoff; //offset from CUT in seconds
    char *tm_zone; //timezone abbreviation
};

5.struct tm与字符串相互转化

使用strftime,将struct tm转化为字符串
函数原型:size_t strftime(char *s,size_t maxsize,char *format,conststruct tm *timeptr)
strftime函数对timeptr指向的tm结构所代表的时间和日期进行格式编排,其结果放在字符串s中。该字符串的长度被设置为(最少)maxsize个字符。格式字符串format用来对写入字符串的字符进行控制,它包含着将被传送到字符串里去的普通字符以及编排时间和日期格式的转换控制符。
例如: strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &tm);
也可自行使用sprintf转化,例如: printf("Current time is %d-%d-%d %d:%d:%d\n", now.tm_year + 1900, now.tm_mon + 1, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec);
使用strptime将字符串转化为struct tm
函数原型:char *strptime(const char *buf,const char*format,struct tm *timeptr)
format字符串的构建方式和strftime的format字符串完全一样,strptime返回一个指针,指向转换过程处理的最后一个字符后面的那个字符

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值