c/c++時間函數學習筆記

1. tm結構時間和time_t時間的轉換

#include <time.h>
#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>

using namespace std;

int main(int argc, char * argv[])
{
    time_t raw_time;
    struct tm *time_info;
    char time_buffer[256];

    raw_time = time(nullptr);
    cout << "The raw_time is " << raw_time << endl;
    time_info = localtime(&raw_time);

    // 將時間轉化爲想要的數據格式
    sprintf(time_buffer, "%4d_%02d_%02d_%02d_%02d_%02d", time_info->tm_year+1900, time_info->tm_mon+1, \
    time_info->tm_mday, time_info->tm_hour, time_info->tm_min, time_info->tm_sec);
    cout << "The time buffer is " << time_buffer << endl;

    // 將時間的年月日放在向量中
    vector<int> time1;
    char *pch;
    pch = strtok(time_buffer,"_");

    while (pch != NULL){
        printf ("%s\n",pch);
        time1.push_back(atoi(pch));
        pch = strtok(NULL, "_");
    }

    // for debug
    /*
    for (vector<int>::iterator it = time.begin(); it != time.end(); it++)
    {
        cout << *it << endl;
    }
    */

    // 將tm結構時間轉化爲time_t時間
    cout << time1[0] << endl;
    struct tm *time_info2 = NULL;
    time_info2 = (struct tm*)malloc(sizeof(struct tm));
    time_info2->tm_year = time1[0] - 1900;
    time_info2->tm_mon = time1[1] - 1;
    time_info2->tm_mday = time1[2];
    time_info2->tm_hour = time1[3];
    time_info2->tm_min = time1[4];
    time_info2->tm_sec = time1[5];
    time_info2->tm_isdst = 0; //夏令時標識符也需要賦值,否則會出錯

    printf( "The time is %4d_%02d_%02d_%02d_%02d_%02d\n", time_info2->tm_year+1900, time_info2->tm_mon+1, \
    time_info2->tm_mday, time_info2->tm_hour, time_info2->tm_min, time_info2->tm_sec);

    time_t cur_time2;
    cur_time2 = mktime(time_info2);
    cout << "The current time is " << cur_time2 << endl;

    sleep(2);
    time_t raw_time3;
    raw_time3 = time(nullptr);

    cout << raw_time3 << endl;

    // difftime 比較兩個時間相差的秒數,前面的秒數比後面大,則返回正數,否則返回負數
    double seconds = difftime(raw_time3, cur_time2);
    cout << "The seconds is " << seconds << endl;
    free(time_info2);
}

夏令時標識符也需要賦值,否則會出錯

運行結果如下:

The raw_time is 1550243429
The time buffer is 2019_02_15_23_10_29
2019
02
15
23
10
29
2019
The time is 2019_02_15_23_10_29
The current time is 1550243429
1550243431
The seconds is 2

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章