[英]How to convert a time_t type to string in C++?
Is it possible to convert a ltm->tm_mday
to string, please ? 可以将
ltm->tm_mday
转换成字符串吗?
I've tried this, but, this wouldn't work ! 我试过这个,但是,这不行!
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);
You can convert time_t
either using complex strftime , either simple asctime functions to char
array and then use corresponding std::string
constructor. 你可以使用复杂的strftime转换
time_t
,简单的asctime函数转换为char
数组,然后使用相应的std::string
构造函数。 Simple example: 简单的例子:
std::string time_string (std::asctime (timeinfo)));
Edit: 编辑:
Specifically for your code, the answer would be: 专门针对您的代码,答案是:
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);
I'm not at all convinced that this is the best way to do it, but it works: 我完全不相信这是最好的方法,但它有效:
#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";
}
The strftime()
function will do most of this work for you, but building up the parts of the string using a stringstream
may be more generally useful. 的
strftime()
函数会做大部分的工作适合你,而是建立使用字符串的部分stringstream
可能更为普遍有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.