红酒手机网站建设,中视频自媒体注册,青岛栈桥附近景点,湖北网站建设服务C11提供了操作时间的库chrono库#xff0c;从语言级别提供了支持chrono库屏蔽了时间操作的很多细节#xff0c;简化了时间操作
Unix操作系统根据计算机产生的年代把1970年1月1日作为UNIX的纪元时间#xff0c;1970年1月1日是时间的中间点#xff0c;将从1970年1月1日起经过…C11提供了操作时间的库chrono库从语言级别提供了支持chrono库屏蔽了时间操作的很多细节简化了时间操作
Unix操作系统根据计算机产生的年代把1970年1月1日作为UNIX的纪元时间1970年1月1日是时间的中间点将从1970年1月1日起经过的秒数用一个整数存放
time_t
time_t用于表示时间类型它是一个 long 类型的别名在time.h文件中定义表示从 1970 年1月1日0时0分0秒到现在的秒数
long tt;
time_t tt;typedef long time_t;time()库函数
time0)库函数用于获取操作系统的当前时间
包含头文件:
#includetime.h声明:
time_t time(time t *tloc);有两种调用方法:
time_t nowtime(0);// 将空地址传递给time()函数并将 time()返回值赋给变量 now。
或
time_t now; time(now);// 将变量 now 的地址作为参数传递给 time()函数。tm结构体
time_t是一个长整数需转换为tm结构体
struct tm
{int tm_sec; /* Seconds. [0-60] (1 leap second) */int tm_min; /* Minutes. [0-59] */int tm_hour; /* Hours. [0-23] */int tm_mday; /* Day. [1-31] */int tm_mon; /* Month. [0-11] */int tm_year; /* Year - 1900. */int tm_wday; /* Day of week. [0-6] */int tm_yday; /* Days in year.[0-365] */int tm_isdst; /* DST. [-1/0/1]*/# ifdef __USE_BSDlong int tm_gmtoff; /* Seconds east of UTC. */const char *tm_zone; /* Timezone abbreviation. */
# elselong int __tm_gmtoff; /* Seconds east of UTC. */const char *__tm_zone; /* Timezone abbreviation. */
# endif
};localtime()库函数
用于把time_t转换为tm结构体表示时间
localtime()函数不是线程安全的licaltime_r()是线程安全的
包含头文件
#includetime.h函数声明:
struct tm *localtime(conmst time_t *timep);
struct tm *localtime_r(const time_t *timep,struct tm * result);示例
#include iostream
#include time.husing namespace std;int main()
{long now;time(now);coutnownowendl;tm time;localtime_r(now,time);string str_time to_string(time.tm_year1900) -to_string(time.tm_mon1) -to_string(time.tm_mday) to_string(time.tm_hour) :to_string(time.tm_min) :to_string(time.tm_sec);couttimestr_timeendl; return 0;
}[rootlocalhost 05demotime]# ./demo_time
now1717311833
time2024-6-2 15:3:53mktime()库函数
mktime函数与localtime()函数相反用于把tm结构体时间转换为time_t时间
包含头文件
#include time.h函数声明
time_t mktime(struct tm *tm);该函数主要用于时间的运算例如 把2022-10-01 15:30:25 加30分钟 思路
解析字符串格式的时间转换为tm结构体用mktime()把time结构体转换成time_t时间把time_t时间加30*60秒把time_t时间转换成tm结构体把tm结构体转换成字符串
gettimeofday()库函数
用于获取1970年1月1日到现在的秒和当前秒中已逝去的微秒数可以用于程序计时
包含头文件
#include sys/time.h函数声明
int gettimeofday(struct timeval *tv,struct timezone *tz);struct timeval{time_t tv_sec; /* Seconds. 1970-1-1到现在秒数 */suseconds_t tv_usec; /* Microseconds. 当前秒中已逝去的微秒数 */};程序睡眠
如果把程序挂起一段时间可以用sleep()和usleep()两个库函数
包含头文件
#includeunistd.h函数声明
unsigned int sleep(unsigned int seconds);
int usleep(useconds_t usec);推荐一个零声学院项目课个人觉得老师讲得不错分享给大家 零声白金学习卡含基础架构/高性能存储/golang云原生/音视频/Linux内核 https://xxetb.xet.tech/s/3Zqhgt