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

运行结果

猜你喜欢

转载自blog.csdn.net/zhouzhenhe2008/article/details/83152574