首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在C++中将time_t类型转换为string?

如何在C++中将time_t类型转换为string?
EN

Stack Overflow用户
提问于 2014-02-06 06:07:13
回答 2查看 12.8K关注 0票数 1

能不能把ltm->tm_mday转换成字符串?

我试过了,但是,这不管用!

代码语言:javascript
复制
time_t now = time(0); 
tm *ltm = localtime(&now); 
String dateAjoutSysteme = ltm->tm_mday + "/" + (1 + ltm->tm_mon) + "/" + (1900 + ltm->tm_year) + " " + (1 + ltm->tm_hour) + ":" + (1 + ltm->tm_min) + ":" + (1 + ltm->tm_sec);
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-02-06 06:17:57

我一点也不相信这是最好的方法,但它是有效的:

代码语言:javascript
复制
#include <time.h>
#include <string>
#include <sstream>
#include <iostream>
int main() {
    time_t now = time(0);
    tm *ltm = localtime(&now);
    std::stringstream date;
    date << ltm->tm_mday
         << "/"
         << 1 + ltm->tm_mon
         << "/"
         << 1900 + ltm->tm_year
         << " "
         << 1 + ltm->tm_hour
         << ":"
         << 1 + ltm->tm_min
         << ":"
         << 1 + ltm->tm_sec;
    std::cout << date.str() << "\n";
}

strftime()函数将为您完成大部分工作,但是使用stringstream构建字符串的各个部分可能更有用。

票数 1
EN

Stack Overflow用户

发布于 2014-02-06 06:14:13

您可以使用复杂的strftime转换time_t,也可以使用简单的asctime函数转换为char数组,然后使用相应的std::string构造函数。简单的例子:

代码语言:javascript
复制
std::string time_string (std::asctime (timeinfo)));

编辑:

具体来说,对于您的代码,答案是:

代码语言:javascript
复制
 std::time_t now = std::time(0);
 tm *ltm = std::localtime(&now); 
 char mbstr[100];
 std::strftime(mbstr, 100, "%d/%m/%Y %T", std::localtime(&t));
 std::string dateAjoutSysteme (mbstr);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21589570

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档