Search code examples
c++datetimec++20c++-chrono

In C++ 20 how do I create a `std::chrono::system_clock::time_point` from specific not const values?


In C++ 20 how do I convert the following struct to a std::chrono::system_clock::time_point?

struct Time {
    //! Year
    unsigned int year;
    //! Month
    unsigned int month;
    //! Day
    unsigned int day;
    //! Hours
    unsigned int hours;
    //! Minutes
    unsigned int minutes;
    //! Seconds
    unsigned int seconds;
};

In other words how do I implement:

std::chrono::system_clock::time_point convert(Time& time) {
    // ?
}

?


Solution

  • Use year/month/day to create a year_month_day object and convert it to sys_days, and then add the corresponding hours/minutes/seconds

    std::chrono::system_clock::time_point convert(const Time& time) {
      using namespace std::chrono;
      return sys_days(
               year_month_day(year(time.year), month(time.month), day(time.day)))
           + hours(time.hours) + minutes(time.minutes) + seconds(time.seconds);
    }
    

    Demo