GXB's Blog

  • 首页
  • 学习笔记
    • C++
    • golang
    • javascript
    • python
  • 工具分享
  • 其它
Kratos
专注于用户阅读体验的响应式博客主题
  1. 首页
  2. 学习笔记
  3. C++
  4. 正文

C++ 时间戳和string相互转换

2026年4月24日 6点热度 1人点赞 0条评论

在现代语言,比如golang或python中时间戳和string之间相互转换是很方便的,C++标准库中没有时间戳和string相互转换的函数,需要我们手动封装一下。

//用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;  
}
标签: 暂无
最后更新:2026年4月24日

admin

这个人很懒,什么都没留下

点赞
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

归档

  • 2026 年 4 月

分类

  • C++
  • golang
  • 学习笔记
  • 工具分享

COPYRIGHT © 2026 GXB's Blog. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang