问题描述
在c ++ 11中以字符串形式获取日期和时间的最新方法是什么?
What is the state of the art way to get date and time as string in c++11?
我知道 std :: put_time
,但是参考文献说我只会在流中使用它。
I know about std::put_time
, but the reference says I shall use it only in streams.
有 std :: chrono :: system_clock
提供了 to_time_t
返回时间为 time_t
并缺少日期,不是吗?
There is std::chrono::system_clock
which provides to_time_t
returning the time as time_t
and lacking the date, doesn't it?
我可以使用类似bames53:,您可以在一行中以 std :: string
的形式获取当前UTC时间。代码:
Using Howard Hinnant's free, open-source header-only datetime library, you can get the current UTC time as a std::string
in a single line of code:
std::string s = date::format("%F %T", std::chrono::system_clock::now());
我刚运行了这个,并且字符串包含:
I just ran this, and the string contains:
2017-03-30 17:05:13.400455
strftime 格式设置标志都可用。如果您希望使用当地时间,也可以使用,尽管它没有
That's right, it even gives you the full precision. If you don't like that format, all of the strftime
formatting flags are available. If you want your local time, there is a timezone library also available, though it is not header only.
std::string s = date::format("%F %T %Z", date::make_zoned(date::current_zone(),
std::chrono::system_clock::now()));
输出:
2017-03-30 13:05:13.400455 EDT
这篇关于C ++ 11以字符串形式获取当前日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!