能不能把ltm->tm_mday转换成字符串?
我试过了,但是,这不管用!
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);发布于 2014-02-06 06:17:57
我一点也不相信这是最好的方法,但它是有效的:
#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构建字符串的各个部分可能更有用。
发布于 2014-02-06 06:14:13
您可以使用复杂的strftime转换time_t,也可以使用简单的asctime函数转换为char数组,然后使用相应的std::string构造函数。简单的例子:
std::string time_string (std::asctime (timeinfo)));编辑:
具体来说,对于您的代码,答案是:
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);https://stackoverflow.com/questions/21589570
复制相似问题