C++ 以 YYYY-MM-DD-HH-MM-SS 字符串的形式获取当前时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5438482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:10:25  来源:igfitidea点击:

Getting the current time as a YYYY-MM-DD-HH-MM-SS string

c++booststring-formattingboost-date-time

提问by ltjax

I'm trying to get the current time as a "YYYY-MM-DD-HH-MM-SS" formatted string in an elegant way. I can take the current time in ISO format from Boost's "Date Time" library, but it has other delimiting strings which won't work for me (I'm using this in a filename). Of course I can just replace the delimiting strings, but have a feeling that there's a nicer way to do this with date-time's formatting options. Is there such a way, and if so, how can I use it?

我试图以一种优雅的方式将当前时间作为“YYYY-MM-DD-HH-MM-SS”格式的字符串。我可以从 Boost 的“日期时间”库中获取 ISO 格式的当前时间,但它有其他对我不起作用的分隔字符串(我在文件名中使用它)。当然,我可以只替换分隔字符串,但感觉有一种更好的方法可以使用日期时间的格式选项来做到这一点。有没有这样的方法,如果有,我该如何使用它?

回答by Null Set

Use std::strftime, it is standard C++.

使用std::strftime,是标准的C++。

#include <cstdio>
#include <ctime>

int main ()
{
    std::time_t rawtime;
    std::tm* timeinfo;
    char buffer [80];

    std::time(&rawtime);
    timeinfo = std::localtime(&rawtime);

    std::strftime(buffer,80,"%Y-%m-%d-%H-%M-%S",timeinfo);
    std::puts(buffer);

    return 0;
}

回答by jbruni

The answer depends on what you mean by get and take. If you are trying to output a formatted time string, use strftime(). If you are trying to parse a text string into a binary format, use strptime().

答案取决于您所说的获取和获取的含义。如果您尝试输出格式化的时间字符串,请使用 strftime()。如果您尝试将文本字符串解析为二进制格式,请使用 strptime()。