我正在创建一个 RFC3339时间戳,包括毫秒和 UTC,在 C++ 中使用 std::chrono
像这样:
#include <chrono>
#include <ctime>
#include <iomanip>
using namespace std;
using namespace std::chrono;
string now_rfc3339() {
const auto now = system_clock::now();
const auto millis = duration_cast<milliseconds>(now.time_since_epoch()).count() % 1000;
const auto c_now = system_clock::to_time_t(now);
stringstream ss;
ss << put_time(gmtime(&c_now), "%FT%T") <<
'.' << setfill('0') << setw(3) << millis << 'Z';
return ss.str();
}
// output like 2019-01-23T10:18:32.079Z
(原谅使用
)
是否有更直接的方法来获取 now
的毫秒数? %1000
now
以毫秒为单位到达那里似乎有些麻烦。或者关于如何更地道地做到这一点的任何其他评论?
最佳答案
你也可以用减法来做:
string
now_rfc3339()
{
const auto now_ms = time_point_cast<milliseconds>(system_clock::now());
const auto now_s = time_point_cast<seconds>(now_ms);
const auto millis = now_ms - now_s;
const auto c_now = system_clock::to_time_t(now_s);
stringstream ss;
ss << put_time(gmtime(&c_now), "%FT%T")
<< '.' << setfill('0') << setw(3) << millis.count() << 'Z';
return ss.str();
}
这避免了“魔数(Magic Number)”1000。
此外,还有 Howard Hinnant's free, open source, single-header, header-only datetime library :
string
now_rfc3339()
{
return date::format("%FT%TZ", time_point_cast<milliseconds>(system_clock::now()));
}
这做同样的事情,但语法更简单。
关于C++ RFC3339 时间戳与毫秒使用 std::chrono,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54325137/