代码说明一切。
strftime给 struct tm结构体的日期的年+1900,月份+1,并按格式转成字符串
std::get_time则对字符串获取struct tm结构体,年份-1900,月份-1
代码如下:
#include
#include
#include
#include
#include
#include
#include
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:%dn",
(*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:%dn", 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
运行结果