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

原文链接: https://www.cnblogs.com/shilipojianshen/p/13305934.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++ string转时间戳

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/366318

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 下午4:38
下一篇 2023年3月2日 下午4:39

相关推荐