简体   繁体   中英

How to get std::chrono::system_clock::time_point from std::chrono::system_clock::time_point.time_since_epoch().count()?

I have a variable stored as a long a value from std::chrono::system_clock::time_point.time_since_epoch().count() . I would now like to restore that std::chrono::system_clock::time_point from the long variable. So how can I convert a long to a std::chrono::system_clock::time_point ?

You first need to convert the integral type to a chrono::duration , and then convert the duration to a system_clock::time_point . But there's a catch:

duration is a template:

template <class Rep, class Period> class duration;

If you convert the integral type to the wrong duration , you'll get the wrong time_point .

Fortunately system_clock itself tells you the correct duration with its nested duration type: system_clock::duration . Additionally, each of these conversions is explicit .

So, in summary:

using namespace std::chrono;
system_clock::time_point tp{system_clock::duration{i}};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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