zoukankan      html  css  js  c++  java
  • C/C++读取时间的方法

    【摘要】本文介绍C/C++下获取日历时间的方法,区别于JAVA语言的方便,C/C++标准库好像并没有一次性得到具有可读性的HH:MM:SS的方法,本文介绍常用的三步法得出具有可读性的时间,并且介绍了纳秒和微秒的时间获取。

    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
    ";
        }
        else{
            cout<<buf<<endl;
        }
    }
    结果:
    date and time:2016-10-05 16:02:45

     5、C/C++中时间数据类型和时间函数的关系

  • 相关阅读:
    Shell 脚本基本操作练习
    Unix 环境高级编程---线程创建、同步、
    ubuntu 安装ssh-server时出现错误:openssh-server: Depends: openssh-client (= 1:5.3p1-3ubuntu3) but 1:5.3p1-3ubuntu4 is to be installed
    python set 集合
    python 深浅拷贝
    用户权限管理
    vim 编辑器的使用
    linux系统初体验
    平滑升级nginx
    在windows下如何使用密钥对远程登录服务器?
  • 原文地址:https://www.cnblogs.com/ycloneal/p/5932468.html
Copyright © 2011-2022 走看看