C/C++读取时间的方法
2016-10-05 16:41
309 查看
【摘要】本文介绍C/C++下获取日历时间的方法,区别于JAVA语言的方便,C/C++标准库好像并没有一次性得到具有可读性的HH:MM:SS的方法,本文介绍常用的三步法得出具有可读性的时间,并且介绍了纳秒和微秒的时间获取。
1、对于C语言,需包含的头文件:
2、获取日期需要先获取日历时间,即1970年1月1日 00:00:00至今的秒数,在linux系统为time_t类型,其相当于1个long型。
然后将time_t转成tm结构体,tm结构体包括分、秒、时、天、月、年等数据。
使用clock_gettime获取日历时间代码如下:
获取日历时间有如下三种:
3、如需获取毫秒和微秒,则不能使用以上的time_t和tm数据,在C/C++中提供了timespec和timeval两个结构供选择,其中timespec包括了time_t类型和纳秒,timeval包括了time_t类型和微秒类型。
4、用易于阅读的方式显示当前日期,C/C++提供strptime函数将time_t转成各类型的时间格式,但是它比较复杂,以下是一个例子:
5、C/C++中时间数据类型和时间函数的关系
1、对于C语言,需包含的头文件:
1 #include <sys/time.h>
2、获取日期需要先获取日历时间,即1970年1月1日 00:00:00至今的秒数,在linux系统为time_t类型,其相当于1个long型。
然后将time_t转成tm结构体,tm结构体包括分、秒、时、天、月、年等数据。
使用clock_gettime获取日历时间代码如下:
#include <iostream> #include <sys/time.h> using namespace std; int main(){ struct timespec tsp; clock_gettime(CLOCK_REALTIME,&tsp); struct tm *tmv = gmtime(&tsp.tv_sec); cout<<"日历时间:"<<tsp.tv_sec<<endl; cout<<"UTC中的秒:"<<tmv->tm_sec<<endl; cout<<"UTC中的时:"<<tmv->tm_hour<<endl; } 结果: 日历时间:1475654852 UTC中的秒:32 UTC中的时:8
获取日历时间有如下三种:
time_t time(time_t *calptr);//精确到秒 int clock_gettime(clockid_t clock_id, struct timespec *tsp);//精确到纳秒 int gettimeofday(struct timeval *restrict tp, void *restrict tzp);//精确到微秒
3、如需获取毫秒和微秒,则不能使用以上的time_t和tm数据,在C/C++中提供了timespec和timeval两个结构供选择,其中timespec包括了time_t类型和纳秒,timeval包括了time_t类型和微秒类型。
#include <iostream> #include <sys/time.h> using namespace std; int main(){ struct timespec tsp; struct timeval tvl; clock_gettime(CLOCK_REALTIME,&tsp); cout<<"timespec中的time_t类型(精度秒):"<<tsp.tv_sec<<endl; cout<<"timespec中的纳秒类型:"<<tsp.tv_nsec<<endl; gettimeofday(&tvl,NULL); cout<<"timeval中的time_t类型(精度秒)"<<tvl.tv_sec<<endl; cout<<"timeval中的微秒类型:"<<tvl.tv_usec<<endl; } 结果: timespec中的time_t类型(精度秒):1475654893 timespec中的纳秒类型:644958756 timeval中的time_t类型(精度秒)1475654893 timeval中的微秒类型:645036
4、用易于阅读的方式显示当前日期,C/C++提供strptime函数将time_t转成各类型的时间格式,但是它比较复杂,以下是一个例子:
#include <iostream> #include <sys/time.h> using namespace std; int main(){ struct timespec tsp; clock_gettime(CLOCK_REALTIME,&tsp); char buf[64]; struct tm *tmp = localtime(&tsp.tv_sec); if (strftime(buf,64,"date and time:%Y-%m-%d %H:%M:%S",tmp)==0){ cout<<"buffer length is too small\n"; } else{ cout<<buf<<endl; } } 结果: date and time:2016-10-05 16:02:45
5、C/C++中时间数据类型和时间函数的关系
相关文章推荐
- C++读取歌词文件(LRC),分解时间和歌词的方法
- visual studio 中C/C++获取计时方法 &Linux 下获取系统时间方法
- C++读取txt文件的方法
- C++获取当前日期时间的方法
- C++中使用Socket通信包定义和读取方法
- c++中常用的计算程序运行时间的方法
- C/C++时间函数使用方法
- c++计算代码执行时间的方法,毫秒级
- vxworks for x86读取bios时间的解决方法
- C/C++ 获取时间间隔的方法
- C++获取毫秒时间的方法
- C/C++时间函数使用方法
- C / C++ 读取文件出现乱码解决方法
- C++ 记录程序运行时间的方法总结
- C++中Txt文件读取和写入(方法汇总)
- C++ 操作64位系统,默认读取Wow6432Node子键的解决方法
- C/C++中读取中文路径文件的方法
- c++中获取系统时间的方法
- C/C++获取本地时间常见方法
- vxworks for x86读取bios时间的解决方法(转)