C ++ 11以字符串形式获取当前日期和时间 [英] C++11 get current date and time as string

查看:562
本文介绍了C ++ 11以字符串形式获取当前日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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 :: chrono在C ++中输出日期和时间但这似乎是一种解决方法。

I could use a stringstream like bames53: Outputting Date and Time in C++ using std::chrono but that seems to be a workaround.

推荐答案

使用霍华德·辛南特(Howard Hinnant)的免费开放源码仅标头日期时间库,您可以在一行中以 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以字符串形式获取当前日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆