Reputation: 29209
I'm obtaining YYYY/MM/DD HH:MM:SS components from an offboard real time clock chip. I want to convert this to a std::chrono::system_clock::timepoint
so that I may obtain the seconds since the Epoch and update the operating system's time.
I would like to use Howard Hinnant's proposed date library to perform this conversion.
I would intuitively do something like this:
date::year_month_day ymd = ...;
date::time_of_day tod = ...;
auto sysTime = date + tod;
but I don't see an appropriate operator+
overload for this. Am I missing something?
Another use case for this type of conversion is to convert a calendar date and time into a std::chrono::timepoint
that I can pass to boost::asio::steady_timer.
Upvotes: 1
Views: 2461
Reputation: 218740
Typically a time_of_day
is just used for formatting a duration into hh:mm:ss.fff
for output. But it is possible to turn a time_of_day
back into a std::chrono::duration
:
auto tod = make_time(hours{17} + minutes{16} + seconds{45}); // time_of_day
auto d = seconds(tod); // seconds
In C++14 I would’ve used the more concise: 17h + 16min + 45s
, but as you mentioned you were in C++11, I’ll stick to C++11 code.
A year_month_day
can be converted into a sys_days
with:
auto ymd = jul/29/2015;
auto dp = sys_days{ymd};
And a sys_days
is nothing but a system_clock::time_point
but with a resolution of days
instead of microseconds
or nanoseconds
.
Then you can add a sys_days
and duration
and assign that to a system_clock::time_point
. Putting it all together:
#include "date.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono;
auto ymd = jul/29/2015;
auto tod = make_time(hours{17} + minutes{16} + seconds{45});
system_clock::time_point tp = sys_days(ymd) + seconds(tod);
}
In this simplified example there is no need to go through time_of_day
, and you could just stay with duration
s:
#include "date.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono;
auto ymd = jul/29/2015;
system_clock::time_point tp = sys_days(ymd)
+ hours{17} + minutes{16} + seconds{45};
}
The main thing to remember is that sys_days
is just a coarse system_clock::time_point
, and when you convert to that from a year_month_day
, then you are completely in the std::chrono
system and can do anything you want with time_point
s and duration
s from there.
Upvotes: 2