Reputation: 11
I want to create a chrono::time_point object for a given date for example : 2020-03-06 22:48:01 where the format is YYYY-MM-DD HH:MM:SS . I do not want to use mktime() as it is not safe. Also I do not want to use any third party library such as date.
Upvotes: 0
Views: 416
Reputation: 218770
For C++11 and C++14, none of the chrono clocks have a specified epoch. However one of them: system_clock
has an epoch that is the same among the three most popular implementations, gcc, llvm and VS. This epoch is 1970-01-01 00:00:00 UTC, excluding leap seconds. This is also known as Unix Time.
While not guaranteed by the C++11/14 standards, you can program to this de-facto standard for std::chrono::system_clock
. But there are no portable epochs for steady_clock
or high_resolution_clock
.
Since you do not want to involve std::tm
, you will have to write your own code to convert YYYY-MM-DD HH:MM:SS
to a count of seconds since the Unix Time epoch. If YYYY-MM-DD HH:MM:SS
is a local time, you will also have to take into account the UTC offset, and the possibility that the UTC offset itself is a function of time for many time zones (i.e. daylight saving time). If YYYY-MM-DD HH:MM:SS
is in string form, you will also need to parse these characters into integral types.
Here are helpful formulas for converting the YYYY-MM-DD
portion of your timestamp into a count of days since the Unix Time epoch.
Slight change in my requirement is that, I am okay to use std::tm but not mktime(). Is there anyway to create std::chrono::time_point object?
If you are starting with data in a stream you could use std::get_time
from <iomanip>
to get the data into a tm
. Then there is a non-standard but popular timegm()
that converts the tm
to a time_t
, neglecting timezones (the original timestamp is interpreted as UTC). And then there is a from_time_t
static member function of system_clock
that will convert the time_t
to system_clock::time_point
.
Hmm... but timegm()
probably qualifies as a 3rd party lib...
Upvotes: 1
Reputation: 473447
All time points are relative to the epoch of the clock that generated them. But in C++14 (and C++17), clock epochs are implementation-specified. Every implementation's clocks have a time point, but there's no way to know what they are. And it makes no sense to ask, since times are all ultimately relative to some fixed date, so the epoch would have to itself be expressed relative to some other date.
So you must either use std::mktime
or a 3rd party library. Or you could just write all the code yourself, but that code wouldn't be able to generate a time point from any particular clock unless it were coded in an implementation-specific fashion.
Upvotes: 0