C++ strftime和std::get_time對linux struct tm的作用

代碼說明一切。

strftime給 struct tm結構體的日期的年+1900,月份+1,並按格式轉成字符串

std::get_time則對字符串獲取struct tm結構體,年份-1900,月份-1

代碼如下:


#include <iostream>
#include <stdio.h>
#include <time.h>
#include <time.h>
#include <iomanip>
#include <ctime>
#include <sstream>
int main()
{
    time_t time_T;
    time_T = time(NULL);
    struct tm *tmTime;
    // tm對象格式的時間
    tmTime = localtime(&time_T);
    printf("\nlocaltime  %d-%d-%d %d:%d:%d\n", 
			(*tmTime).tm_year ,
			(*tmTime).tm_mon, 
			(*tmTime).tm_mday,
			(*tmTime).tm_hour, 
			(*tmTime).tm_min,
			(*tmTime).tm_sec);

    const char* format = "%Y-%m-%d %H:%M:%S";
    char strTime[100];
    strftime(strTime, sizeof(strTime), format, tmTime);
    printf("\nlocaltime  atfter strftime  string %s \n",strTime );
	
    struct tm  time_struct;
    std::istringstream ss(strTime);
    ss>> std::get_time(&time_struct, "%Y-%m-%d %H:%M:%S");
	printf("\nstd::get_time  %d-%d-%d %d:%d:%d\n", time_struct.tm_year , 
								time_struct.tm_mon ,
								time_struct.tm_mday,
								time_struct.tm_hour, 
								time_struct.tm_min ,
								time_struct.tm_sec); 
    return 0;
}

 

編譯,需要C++11以上

         g++ New0001.cpp -std=c++11

 

運行結果

 

 

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