Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在C+中将时间类型转换为字符串+;?_C++_String_Ctime - Fatal编程技术网

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