1. 程式人生 > >c++ %d-%d-%d %d:%d:%d 轉unix時間戳

c++ %d-%d-%d %d:%d:%d 轉unix時間戳

最近的業務,需要用到string轉UNIX時間戳,記錄一下實現過程

c++程式碼如下:


#include <stdio.h> 
#include <memory.h>
#include <iostream>  
#include <ctime>
#include <string>
 
  
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