天天看點

c語言 時間字元串格式轉換,時間字元串格式互相轉換——C語言

#include

#include

#include

#include

#include

#include

using namespace std;

typedef time_t TIME;

string ToStrTime(TIME timestamp)

{

char buffer[80];

strftime(buffer , sizeof(buffer) , "%Y-%m-%d %H:%M:%S" , localtime(×tamp));

return string(buffer, 0, strlen(buffer));

}

TIME ToTimeStamp(string strTime)

{

tm _tm;

int year, month, day, hour, minute,second;

sscanf(strTime.c_str(), "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &second);

_tm.tm_year = year - 1900;

_tm.tm_mon = month - 1;

_tm.tm_mday = day;

_tm.tm_hour = hour;

_tm.tm_min = minute;

_tm.tm_sec = second;

_tm.tm_isdst = 0;

time_t t = mktime(&_tm);

return t;

}

void test()

{

TIME nowTime;

time(&nowTime);

string strTime = ToStrTime(nowTime);

cout << "now time: " << strTime << endl;

TIME t = ToTimeStamp(strTime);

assert(nowTime == t);

}

int main ()

{

test();

return 0;

}