您好,登錄后才能下訂單哦!
這篇文章主要介紹了linux下c++怎么實(shí)現(xiàn)string與time_t互相轉(zhuǎn)換的相關(guān)知識(shí),內(nèi)容詳細(xì)易懂,操作簡(jiǎn)單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇linux下c++怎么實(shí)現(xiàn)string與time_t互相轉(zhuǎn)換文章都會(huì)有所收獲,下面我們一起來(lái)看看吧。
代碼如下:
#include <time.h> #include <string> #include <iostream> using namespace std; time_t string2time_t(const string string_time); string time_t2string(const time_t time_t_time); int main() { string strTime = "2014/03/28 18:25:26"; time_t time1 = string2time_t(strTime); cout<<time1<<endl; time_t time2 = time(NULL); string strNowTime = time_t2string(time2); cout<<strNowTime<<endl; getchar(); return 1; } //string 轉(zhuǎn)換為time_t 時(shí)間格式為2014/03/28 18:25:26 time_t string2time_t(const string string_time) { tm tm1; memset(&tm1, 0, sizeof(tm1)); time_t time1; sscanf_s(string_time.c_str(), "%d/%d/%d/ %d:%d:%d", &(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 -= 1; time1 = mktime(&tm1); return time1; } //time_t轉(zhuǎn)換為string 時(shí)間格式為2014/03/28 18:25:26 string time_t2string(const time_t time_t_time) { char szTime[100] = {'\0'}; tm *pTm = new tm; localtime_s(pTm, &time_t_time); //pTm = localtime(&time_t_time); pTm->tm_year += 1900; pTm->tm_mon +=1; sprintf_s(szTime, "%04d/%02d/%02d %02d:%02d:%02d", pTm->tm_year, pTm->tm_mon, pTm->tm_mday, pTm->tm_hour, pTm->tm_min, pTm->tm_sec); string strTime = szTime; delete pTm; pTm = NULL; return strTime; }
string get_time() { string timeStr; //time_t t = time(0); time_t t = time(NULL); char tmp[64]; strftime( tmp, sizeof(tmp), "%Y-%m-%d %X ",localtime(&t) );// 2017-05-16 17:00:00 timeStr = tmp; return timeStr; }
time_t convert_string_to_time_t(const std::string & time_string) { struct tm tm1; time_t time1; sscanf(time_string.c_str(), "%d-%d-%d %d:%d:%d" , &(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 --; tm1.tm_isdst=-1; time1 = mktime(&tm1); return time1; }
關(guān)于“l(fā)inux下c++怎么實(shí)現(xiàn)string與time_t互相轉(zhuǎn)換”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對(duì)“l(fā)inux下c++怎么實(shí)現(xiàn)string與time_t互相轉(zhuǎn)換”知識(shí)都有一定的了解,大家如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。