Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an std::chrono::time_point for 1 Jan 1970 00:00:00?

Tags:

c++

time

chrono

Is there a portable standard-compliant way to create an std::chrono::time_point for 1 Jan 1970 00:00:00? This has to be thread-safe. Therefore, the solution should avoid functions like std::gmtime() and std::localtime() which do not have thread-safety guarantees.

This is not a duplicate of Convert std::chrono::time_point to unix timestamp since I'm asking for a portable solution that is thread-safe. Neither does the question there ask for that, nor do the answers provide this guarantee.

like image 351
Ralph Tandetzky Avatar asked Nov 04 '16 11:11

Ralph Tandetzky


People also ask

What is std :: Chrono :: Time_point?

Class template std::chrono::time_point represents a point in time. It is implemented as if it stores a value of type Duration indicating the time interval from the start of the Clock 's epoch. Clock must meet the requirements for Clock or be std::chrono::local_t (since C++20).

What does std :: Chrono :: System_clock :: now return?

std::chrono::system_clock::now Returns a time point representing with the current point in time.

What is Chrono used for C++?

Chrono in C++ Chrono library is used to deal with date and time. This library was designed to deal with the fact that timers and clocks might be different on different systems and thus to improve over time in terms of precision.

What is time_ since_ epoch in c++?

constexpr duration time_since_epoch() const; (since C++14) Returns a duration representing the amount of time between *this and the clock 's epoch.


1 Answers

In practise, std::chrono::system_clock::from_time_t(0) will return the value you want.

In principle, I can't see how to exactly what you want.

As an alternative, calculate this value once (at startup) before multiple threads have started running.

like image 128
Martin Bonner supports Monica Avatar answered Oct 17 '22 07:10

Martin Bonner supports Monica