仅使用C++中的标准库获取以毫秒为单位的当前日期和时间

Get the current date and time with milliseconds with only the standard library in C++

本文关键字:为单位 当前日期 时间 C++ 标准 获取      更新时间:2023-10-16

我正在尝试打印这样的时间戳。

2018-05-24T20:16:07.339271

我不想使用 Boost 或任何第三方库。我只想使用标准库。我正在使用 Clang 6,所以如有必要,我应该可以使用 C++ 17。

我开始看chrono,有这样的东西。

auto now = std::chrono::high_resolution_clock::now();

但是,我不确定如何从上面获得我想要的日期时间格式。

以下代码仅使用标准C++。*loc_timemilli_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);