这篇文章主要讲解了“c++如何实现string与time_t互相转换”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“c++如何实现string与time_t互相转换”吧!
代码如下:
#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 转换为time_t 时间格式为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转换为string 时间格式为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; }
感谢各位的阅读,以上就是“c++如何实现string与time_t互相转换”的内容了,经过本文的学习后,相信大家对c++如何实现string与time_t互相转换这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。