C++ string转时间戳


若配置文件中存在一个过期时间,需要与当前时间比较配置是否过期需要将配置时间和当前时间进行比较

C中存在ctime类,

//用time()取得当前时间 (秒数), 利用localtime() 转换成struct tm 再利用mktime()将struct tm转换成原来的秒数。
#include <time.h>
main(){
    time_t timep;
    struct tm *p;
    time(&timep);
    printf("time() : %d \n", timep);
    p = localtime(&timep);
    timep = mktime(p);
    printf("time()->localtime()->mktime():%d\n", timep);
}

另外还有将string类型的设定时间转换为unix时间戳

#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;  
}   

参考:http://c.biancheng.net/cpp/html/145.html:https://blog.csdn.net/shine_journey/article/details/70173947


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM