How to serialize a time_point?
Apr 18, 2018 at 10:26pm UTC
Having this code:
1 2 3 4 5 6 7 8 9 10
namespace date
{
using days = std::chrono::duration<int , std::ratio_multiply<std::ratio<24>,
std::chrono::hours::period>>;
template <class Duration>
using sys_time =std::chrono::time_point<std::chrono::system_clock, Duration>;
using sys_days = sys_time<days>;
}
I have a a sys_days stored in a database as an integer field. I need to transform int to sys_days and sys_days to int. The only problem is that sys_days (being a time_point) has its representation as a private _Duration.
1 2 3 4 5
date::sys_days int_to_sysdays(int val)
{
date::sys_time<date::days> d = val; // HOW???
return d;
}
Regards,
Juan Dent
Apr 18, 2018 at 11:44pm UTC
I haven't tested this but this should be the general idea.
serialize:
std::chrono::duration_cast<date::days>(std::chrono::system_clock::now() - tp.time_since_epoch()).count();
deserialize:
std::chrono::duration_cast<date::days>(tp.time_since_epoch() + date::days(val)).count();
Apr 19, 2018 at 1:03am UTC
In deserialize, where do we get tp from? The name of this function would be something like 'date::sys_days int_to_sysdays(int val)'
This does not work:
date::sys_days tp = std::chrono::duration_cast<date::days>(date::days(val)).count();
I get error:
error C2440: 'initializing': cannot convert from 'date::days' to 'std::chrono::time_point<std::chrono::system_clock,date::days>'
In serialize, where do we get tp from? The name of this function would be like 'int sysdays_to_int(date::sys_days days)'
std::chrono::duration_cast<date::days>(std::chrono::system_clock::now() - days.time_since_epoch()).count();
Last edited on Apr 19, 2018 at 1:13am UTC
Apr 19, 2018 at 3:23am UTC
Yea I didn't know what I was writing.
.count should be returning an int, I believe.
I actually tested this for once.
1 2 3 4 5 6 7
int main()
{
int i = std::chrono::duration_cast<date::days>(std::chrono::system_clock::now().time_since_epoch()).count();
std::chrono::system_clock::time_point tp(date::days(i));
std::cout << "Hello, " << std::chrono::duration_cast<date::days>(date::days(i)).count() << "!\n" ;
}
Apr 19, 2018 at 9:40pm UTC
Hi poteto,
I got the first code correct:
1 2 3 4 5
int sysdays_to_int(date::sys_days days)
{
int i = std::chrono::duration_cast<date::days>(days.time_since_epoch()).count();
return i;
}
but the other conversion function is still unknown to me:
1 2 3 4
date::sys_days int_to_sysdays(int val)
{
/// ??????
}
Could you please help?
Apr 19, 2018 at 10:31pm UTC
I think I got it:
1 2 3 4 5 6
date::sys_days int_to_sysdays(int val)
{
std::chrono::time_point<std::chrono::system_clock, date::days> tp{};
tp += date::days{ val };
return tp;
}
Right?
Juan
Topic archived. No new replies allowed.