[C++]关于时间的转换和获取

来源:互联网 发布:欧洲女装品牌 知乎 编辑:程序博客网 时间:2024/05/21 08:57

cpp中并没有直接的时间的类库,而是继承了c中的ctime类。

c语言提供了4中日期和时间的类型:time_t,clock_t,size_t,tm。
其中time_t,clock_t,size_t是能够代表系统的时间和日期的整型数。

tm是一个结构体,如下所示:

struct tm {   int tm_sec;   // 秒,0-59   int tm_min;   // 分,0-59   int tm_hour;  // 时,0-24   int tm_mday;  // 月日,1-31   int tm_mon;   // 年月,0-11   int tm_year;  // 年,从1900始   int tm_wday;  // 星期,以星期日为始   int tm_yday;  // 天,1月1日始   int tm_isdst; // 夏令时}

下面介绍的是标准c/c++库里的方法:

方法名 说明 time_t time(time_t *time) 从1970年1月1日到到现在的秒数,如果系统时间不存在,返回1 char *ctime(const time_t *time) 返回以:day month year hours:minutes:seconds year\n\0格式的时间字符串指针 struct tm *localtime(const time_t *time) 返回现在时间的tm结构体的指针 clock_t clock(void) 返回程序调用到现在的时间,1为不可用 char * asctime ( const struct tm * time) 返回time为名的结构体转换为的字符串指针,格式为:day month date hours:minutes:seconds year\n\0 struct tm *gmtime(const time_t *time) 返回tm结构体指针的UTC时间 time_t mktime(struct tm *time) 返回time结构提指针中与日历时间相等的时间 double difftime ( time_t time2, time_t time1 ) 比较1和2两个时间的差值 size_t strftime() 格式化时间

测试程序如下:

#include <iostream>#include <ctime>using namespace std;int main(int argc, char *argv[]){    //utc local    time_t timeNow=time(0);    char* timeString=ctime(&timeNow);    cout<<"time local is "<<timeString<<endl;    tm* utcTime=gmtime(&timeNow);    timeString=asctime(utcTime);     cout<<"time utc is "<<timeString<<endl;    //mktime     time_t mkTime=mktime(utcTime);    char* timeString1=ctime(&mkTime);      cout<<"time mk is "<<timeString1<<endl;     cout<<"work finished"<<endl;     //time format     time_t now = time(0);     cout << "secs fomr 1970 1 1:" << now << endl;     tm *ltm = localtime(&now);     // print various components of tm structure.     cout << "Year:" << 1900 + ltm->tm_year<<endl;     cout << "Month: "<< 1 + ltm->tm_mon<< endl;     cout << "Day: "<<  ltm->tm_mday << endl;     cout << "Time: "<< 1 + ltm->tm_hour << ":";     cout << 1 + ltm->tm_min << ":";     cout << 1 + ltm->tm_sec << endl;    return 0;}

以上。

0 0