C++ 如何在C+中将时间类型转换为字符串+;?
是否可以将C++ 如何在C+中将时间类型转换为字符串+;?,c++,string,ctime,C++,String,Ctime,是否可以将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
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);
您可以使用复杂函数或简单函数将
time\t
转换为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);
我一点也不相信这是最好的方法,但它是有效的:
#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";
}
#包括
#包括
#包括
#包括
int main(){
现在时间=时间(0);
tm*ltm=localtime(&now);
std::stringstream日期;
日期TMmday
查看strftime()
。不确定是否有更像C++的方法。C++11:std::stringstream buf;buf以毫秒为单位获取它-请注意,这在技术上是“不正确的”,因为它假定time\u t
是一个整数,但这是唯一快速实现它的方法…:std::To\u string(现在)因为我不明白你说的是什么:因为我不明白你说了什么:“代码> STD::ActhTime/Cuth>而不是<代码> ActhTime/Cuth>?@ KeththpP生森最初我想到的是简单的<代码> ActhTime/Cuth>但是看起来C++更适合写<代码>:ST::/Cord>一个。@ PrordnIK:我的理解是lude
给你asctime
可能给你std::asctime
,也可能不给你include
给你std::asctime
,也可能不给你asctime
。这很难看,但事实就是这样。@Predelnik,把它应用到我的例子中,比如Keith Thompson,来验证结果。好的,谢谢你,如何将date
转换为str::string?@user3264174,查看答案。@user3264174:str()
方法从std::stringstream
返回std::string
。