繁体   English   中英

仅使用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();

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

猜猜你最好的选择是使用std::localtime + std::put_time

以下代码仅使用标准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;
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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM