3/19/10

c++ Unix time to string / string to Unix time

Unix time to string:


double doubleUnixTime = 1268974800;
string stringUnixTime;
time_t unixTime = doubleUnixTime ;
doubleUnixTime = asctime(gmtime(&unixTime));


Datetime String to unix time:
Datetime string in this format: yyyy-mm-dd hh:mm:ss

string stringDateTime = "2010-01-11 11:42:58";
struct tm *tmp = new tm;

time_t rawtime;
time ( &rawtime );
tmp = localtime ( &rawtime );

string year = stringDateTime.substr(0,4);
string month = stringDateTime.substr(5,2);
string day = stringDateTime.substr(8,2);
string hour = stringDateTime.substr(11,2);
string min = stringDateTime.substr(14,2);
string sec = stringDateTime.substr(17,2);

if(year != "0000")
tmp->tm_year = atoi(year.c_str()) - 1900;
else
tmp->tm_year = 0;

if(month != "00")
tmp->tm_mon = atoi(month.c_str()) - 1;
else
tmp->tm_mon = 0;

if(day != "00")
tmp->tm_mday = atoi(day.c_str());
else
tmp->tm_mday = 0;

tmp->tm_hour = atoi(hour.c_str());

tmp->tm_min = atoi(min.c_str());

tmp->tm_sec = atoi(sec.c_str());

rawtime = mktime(tmp);

int intRawtime = rawtime;


5 comments: