C语言 C - 将 time_t 转换为格式为 YYYY-MM-DD HH:MM:SS 的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3053999/
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-09-02 05:40:48  来源:igfitidea点击:

C - Convert time_t to string with format YYYY-MM-DD HH:MM:SS

c

提问by dmessf

Is there any way to convert a time_tto a std::stringwith the format YYYY-MM-DD HH:MM:SSautomatically while keeping the code portable?

有没有什么办法的转换time_t到一个std::string格式为YYYY-MM-DD HH:MM:SS自动同时保持代码的可移植性?

回答by Jerry Coffin

Use localtimeto convert the time_tto a struct tm. You can use strftimeto print the desired data from that.

用于localtime将 转换time_tstruct tm。您可以使用它strftime来打印所需的数据。

char buff[20];
time_t now = time(NULL);
strftime(buff, 20, "%Y-%m-%d %H:%M:%S", localtime(&now));

回答by jer

Your only real option off the top of my head is either to write your own routine, or use the ctime() function defined in POSIX.1/C90. ctime() is certainly worth looking into, but if your date is not in the right timezone already, you will run into issues.

你唯一真正的选择是编写自己的例程,或者使用 POSIX.1/C90 中定义的 ctime() 函数。ctime() 当然值得研究,但如果您的日期不在正确的时区,您将遇到问题。

EDIT: I didn't think about using localtime as mentioned by Jerry below. Converting it to a struct tm does give you more possibilities including what he mentions, and strptime().

编辑:我没有考虑使用下面 Jerry 提到的 localtime。将其转换为 struct tm 确实为您提供了更多可能性,包括他提到的内容和 strptime()。