Search code examples
c++castingc++14c++-chrono

How to cast from utc_time<seconds> to utc_time<days>


I want to load utc_time< days > variable with year, month, day.
I do not know how to cast the result 'x' from date::utc_seconds to utc_time< days > and in general how to cast e.g. utc_time< milliseconds > to utc_time< days >...

auto x = to_utc_time(sys_days(year_month_day{ year{y}, month(m), day(d) }));
utc_time<days> utc_tp = ?x?; // now x => date::utc_seconds

Solved: utc_time< days > utc_tp = time_point_cast< days >(x);

time_point_cast casts from fine precision time_point to a coarser precision time_point.


Solution

  • In addition to time_point_cast<days>, which truncates towards the epoch, there is also available:

    • floor<days>(x) : truncate to the beginning of the current day.

    • ceil<days>(x) : truncate to the beginning of the next day.

    • round<days>(x) : truncate to the closest day boundary.

    time_point_cast<days>(x) is equivalent to floor<days>(x) when x is after the 1970-01-01 epoch, and equivalent to ceil<days>(x) when x is prior to the 1970-01-01 epoch.