日期與時間(C/C++)


C++繼承了C語言用於日期和時間操作的結構和函數,使用之前程序要引用<ctime>頭文件

有四個與時間相關的類型:clock_t、time_t、size_t、和tm。類型clock_t、size_t、和time_t能夠把系統時間和日期表示為某種整數。

結構體tm把時間和日期以C結構的形式保存,tm結構的定義如下:

struct tm
{
    int tm_sec; //秒,正常范圍0 ~59,但是允許到61
    int tm_min; //分 范圍 0~59
    int tm_hour; //小時 0~23
    int tm_mday;    //一月中的第幾天
    int tm_mon;    //月 0~11
    int tm_year;    //自1900年起的年數
    int tm_wday;    //一周中的第幾天
    int tm_yday;    //一年中的第幾天
    int tm_isdst; //夏令時    
}

相關函數:

函數

描述

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 year hours:minutes:seconds year\n\0

struct tm *gmtime(const time_t *time);

該函數返回一個指向time的指針,time為tm結構,用協調世界時(UTC)也被稱為格林尼治標准時間(GMT)表示

time_t mktime(struct tm *time);

該函數返回日歷時間,相當於time所指向結構中存儲的時間

double difftime(time_t time2,time_t time1);

該函數返回time1和time2之間相差的秒數

size_t strftime();

該函數可用於格式化日期和時間為指定的格式

實例:

#include<iostream>
#include<ctime>
using namespace std;

int main()
{
    //基於當前系統日期和時間 初始化0
    time_t now = time(0);

    /把now轉換成字符串形式
    char *dt = ctime(&now);

    cout << "local date and time:  " << dt << endl;

    //把now轉化成tm結構
    tm *gmtm = gmtime(&now);
    dt = asctime(gmtm);
    cout << "UTC date and time :  " << dt << endl;
    return 0;
}

運行結果:

exbot@ubuntu:~/wangqinghe/C++/time$ ./time

local date and time:  Mon Aug  5 14:54:25 2019

 

UTC date and time :  Mon Aug  5 06:54:25 2019

 

使用結構體tm格式化時間

#include<iostream>
#include<ctime>
using namespace std;

int main()
{
    time_t now = time(0);
    
    cout << "from 1970  then the seconds passed : " << now << endl;

    tm* ltm = localtime(&now);

    cout << "year : " << 1900 + ltm->tm_year << endl;
    cout << "month : " << 1 + ltm->tm_mon << endl;
    cout << "day : " << ltm->tm_mday << endl;
    cout << "hour : " << ltm->tm_hour << ":";
    cout << ltm->tm_min << ":";
    cout << ltm->tm_sec << endl;
    return 0;
}

運行結果:

exbot@ubuntu:~/wangqinghe/C++/time$ ./time1

from 1970  then the seconds passed : 1564988067

year : 2019

month : 8

day : 5

hour : 14:54:27

 

以20xx-xx-xx xx:xx:xx格式輸出結果:

#include<iostream>
#include<ctime>
#include<cstdlib>
#include<cstdio>

using namespace std;

string Get_Current_Date();

int main()
{
    cout << Get_Current_Date().c_str() << endl;
    return 0;
}

string Get_Current_Date()
{
    time_t nowtime;
    nowtime = time(NULL);
    char tmp[64];
    strftime(tmp,sizeof(tmp),"%Y-%m-%d %H:%M:%S",localtime(&nowtime));
    return tmp;
}

運行結果:

exbot@ubuntu:~/wangqinghe/C++/time$ ./time2

2019-08-05 15:00:14


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM