仅使用C++中的标准库获取以毫秒为单位的当前日期和时间
Get the current date and time with milliseconds with only the standard library in C++
我正在尝试打印这样的时间戳。
2018-05-24T20:16:07.339271
我不想使用 Boost 或任何第三方库。我只想使用标准库。我正在使用 Clang 6,所以如有必要,我应该可以使用 C++ 17。
我开始看chrono
,有这样的东西。
auto now = std::chrono::high_resolution_clock::now();
但是,我不确定如何从上面获得我想要的日期时间格式。
以下代码仅使用标准C++。*loc_time和milli_secs中包含的数据可用于在本地时间产生所需的输出。要获取 UTC 格式的输出,请使用 std::gmtime 而不是 std::localtime。
// get actual system time
const auto now = std::chrono::system_clock::now();
// get seconds since 1970/1/1 00:00:00 UTC
const auto sec_utc = std::chrono::system_clock::to_time_t(now);
// get pointer to tm struct (not thread safe!)
const auto loc_time = std::localtime(&sec_utc);
// get time_point from sec_utc (note: no milliseconds)
const auto now_s = std::chrono::system_clock::from_time_t(sec_utc);
// get milliseconds (difference between now and now_s
const auto milli_secs = std::chrono::duration<double, std::milli>(now - now_s).count() * .001;
猜你最好的选择是使用std::localtime
+std::put_time
standard library c++ does not provide a proper date type, so you can use
structs and functions from c which is inherited on c++. <ctime> header
file need to include in c++ program. i think below code will help you.
time_t now = time(0);
cout<<now<<endl;
tm *lt = localtime(&now);
相关文章:
- 如何找到两个日期之间的时间差异(以秒和纳秒为单位)?
- 仅使用C++中的标准库获取以毫秒为单位的当前日期和时间
- C++以微秒为单位解析日期/时间
- 使用 c++ 获取两个日期与时间字符串之间的差异(以秒为单位)
- 如何以毫秒为单位获得当前时间
- 如何获取自C++纪元 (MSVS) 以来的本地当前时间(以秒为单位)
- 如何从1970年1月1日(C++)开始获取当前系统时间(以毫秒为单位)
- 文件名为自c++中的epoch以来的当前时间(以秒为单位)
- 在 C++ 中以毫秒为单位将日期转换为时间
- 以 C++ 为单位获取当前时间(以月/日/年为单位)
- 如何以毫秒为单位获取自 1970 年以来的当前时间戳,就像 Java 一样
- 使用 c++ chrono 以纳秒为单位打印当前系统时间
- 以 Qt 为单位的日期时间
- 将 Unix 时间戳(以毫秒为单位)转换为正常日期
- 根据您的出生日期,您的年龄以月为单位
- 与std::chrono::system_clock完全分隔的日期(以毫秒为单位)
- 如何使用"time.h"库(仅)以毫秒为单位获取当前时间?
- 函数返回当前日期(月和日均为零)
- 设计一个结构来存储时间和日期.写一个函数来计算两个时间之间的差(以分钟为单位)
- 如何以秒为单位获取系统的当前日期时间