c++ %d-%d-%d %d:%d:%d 转unix时间戳

最近的业务,需要用到string转UNIX时间戳,记录一下实现过程

c++代码如下:


#include  
#include
#include  
#include
#include
 
  
time_t strTime2unix(std::string timeStamp)  
{  
    struct tm tm;  
    memset(&tm, 0, sizeof(tm));  
      
    sscanf(timeStamp.c_str(), "%d-%d-%d %d:%d:%d",   
           &tm.tm_year, &tm.tm_mon, &tm.tm_mday,  
           &tm.tm_hour, &tm.tm_min, &tm.tm_sec);  
  
    tm.tm_year -= 1900;  
    tm.tm_mon--;  
  
    return mktime(&tm);  
}  
  
int main()  
{  
    std::string str = "2017-04-14 16:41:40";  
    time_t t = strTime2unix(str);
    std::cout << t << std::endl;  
    std::cout << ctime(&t) << std::endl;  
  
    return 0;  
}   
 
结果如下图:

[参考文献]

[1] http://blog.csdn.net/stpeace/article/details/49008877

你可能感兴趣的:(c++,string,转unix时间戳)