使用字符串流格式化日期 [英] Formatting dates with stringstream
问题描述
我想避免在我的 C++ 代码中使用 sprintf,所以我只能使用 C++ 中的 std 字符串,但我还没有找到替换它的方法.我目前使用 sprintf 来格式化日期和时间,如下所示:
I want to avoid the usage of sprintf in my C++ code so I can use only std strings from C++, but I haven't found the way to replace it yet. I currently use sprintf to format dates and times like this:
char myDate[DATE_LENGTH]{};
sprintf(myDate, "%4d-%02d-%02d %02d:%02d:%02d", year, month, day,
hour, minute, second);
通过这种方式,我将为每个整数获得固定长度,如果需要,可以使用前导零.
In this way, I will get a fixed length for each integer, with leading zeros if needed.
我已经搜索了如何用 stringstream 替换它,并找到了这个:
I have searched how to replace this with stringstream, and found this:
std::ostringstream ss;
ss << std::setw(5) << std::setfill('0') << 12 << "\n";
但这只会格式化其中一个整数.我需要为每个日期和时间组件执行此操作,然后将它们全部附加在一起.所以要替换一行 C 风格的代码,我需要更多的新代码.
But this only would format one of the integers. I would need to do this for each date and tiem component and then append all of them together. So to replace one line of C-style code, I would need much more new code.
没有比这更好的方法了吗?
Is not there any way to do better than this?
推荐答案
(1) 定义您自己的数据时间类.
(1) Define your own datatime class.
(2) 为其定义operator <<()
和operator >>()
.在这些函数中,使用std::time_put
和std::time_get
facet来实现.
(2) Define the operator <<()
and operator >>()
for it. In these function, use std::time_put
and std::time_get
facet to implement.
(3) 如果std::time_put
和std::time_get
不能满足你的需求,你可以通过继承定义你自己的time_put/get facet, 以及其他辅助方面,例如 date_time 格式管理器(如有必要).
(3) If the std::time_put
and std::time_get
can't satisfy your needs, you can define your own time_put/get facet by inheriting them, and other assistant facet such as date_time format manager if necessary.
PS:如果您使用的是 c++11,std::time_put::put()
和 std::time_get::get()
可能是满意.
PS: If you're using c++11, std::time_put::put()
and std::time_get::get()
may be satisfied.
祝你好运!
这篇关于使用字符串流格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!