string字符串格式化成time_t,并计算2个time_t的时间差
#include "time.h" #include <iostream> #include <string> using namespace std; time_t string2time(const string & time_string) { struct tm tm1; time_t time1; sscanf(time_string.c_str(), "%d-%d-%d T%d:%d:%dZ" , &(tm1.tm_year), &(tm1.tm_mon), &(tm1.tm_mday), &(tm1.tm_hour), &(tm1.tm_min), &(tm1.tm_sec)); tm1.tm_year -= 1900; tm1.tm_mon --; time1 = mktime(&tm1); return time1; } string double2TimeString(double dTime) { int iHour = dTime/60/60; int iMin = (dTime - iHour*60*60)/60; int iSec = dTime - iHour*60*60 - iMin*60; char buffer[10]; sprintf(buffer,"%02d:%02d:%02d",iHour, iMin , iSec); string strTemp = buffer; return strTemp; } int main() { string strStartTime = "2014-08-31 T13:20:58Z"; string strEndTime = "2014-08-31 T15:12:32Z"; cout<<strStartTime<<endl; cout<<strEndTime<<endl; time_t tStartTime = string2time(strStartTime); time_t tEndTime = string2time(strEndTime); //返回两个时间相差的秒数 double dTime = difftime(tEndTime, tStartTime); string strTime = double2TimeString(dTime); cout<<"时间间隔:"<<strTime<<endl; return 0; }
效果图: