如何让此函数返回日期时间字符串

时间:2016-06-02 20:45:20

标签: c++ datetime

我有以下功能,对于我的生活,我无法返回一个字符串:

void GetDateTimeString()
{
    auto t1 = std::time(nullptr);
    auto tm1 = *std::localtime(&t1);
    stringstream dattim1;
    cout << put_time(&tm1, "%Y-%m-%d_%H-%M-%S");
}

我徒劳地试过这个,这使程序崩溃了:

std::string GetDateTimeString()
{
    time_t t1 = std::time(nullptr);
    tm tm1 = *std::localtime(&t1);
    stringstream dattim1;
    dattim1 << put_time(&tm1, "%Y-%m-%d_%H-%M-%S");
    std::string returnValue = dattim1.str();
    return returnValue;
}

最后我想这样称呼它:

string dateString = GetDateTimeString();

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您的函数的第一个版本是void类型,因此它不会返回任何内容。 cout只打印时间,例如到控制台。

在第二个功能中,您尝试再次使用put_time,但这对您的需求来说是错误的功能。而是使用strftime将时间复制到char-array,然后复制到string

std::string GetDateTimeString()
{
    time_t t1 = std::time(nullptr);
    tm tm1 = *std::localtime(&t1);
    char buffer[80];
    strftime(buffer, sizeof(buffer), "%Y-%m-%d_%H-%M-%S", &tm1);
    std::string returnValue(buffer);
    return returnValue;
}

答案 1 :(得分:0)

由于代码在一个简单的测试中工作,但在你的应用程序中崩溃,我建议你看一下使用localtime_s或localtime_r(取决于系统)而不是localtime,它返回一个指向静态缓冲区的指针,而不是线程安全的。