Home > Article > Backend Development > How do you extract specific temporal units from a chrono::time_point in C ?
Extracting Temporal Units from Chrono Time Points
In C , extracting precise temporal units from an std::chrono::time_point object depends on the underlying clock type. The system_clock, which has a connection to the civil calendar, enables accessing data like year, month, day, and millisecond.
To obtain a system_clock::time_point representing the current time:
<code class="cpp">std::chrono::system_clock::time_point now = std::chrono::system_clock::now();</code>
Convert it to a time_t and then to a tm struct using the C library. This conversion option can be either in UTC or the local time zone:
<code class="cpp">std::time_t tt = std::chrono::system_clock::to_time_t(now); std::tm utc_tm = *std::gmtime(&tt); std::tm local_tm = *std::localtime(&tt);</code>
You can then extract the desired temporal components, for example:
<code class="cpp">int year = local_tm.tm_year + 1900; int month = local_tm.tm_mon + 1; int day = local_tm.tm_mday;</code>
Additionally, system_clock is often based on Unix time, providing access to fractional seconds:
<code class="cpp">int frac_second = std::chrono::system_clock::duration::period::num / std::chrono::system_clock::duration::period::den;</code>
The duration_cast and custom duration class days can be utilized to facilitate precise time calculations:
<code class="cpp">std::chrono::duration<int, std::ratio_multiply<std::chrono::hours::period, std::ratio<24>>> days; std::chrono::days d = std::chrono::duration_cast<std::chrono::days>(tp); tp -= d; std::chrono::hours h = std::chrono::duration_cast<std::chrono::hours>(tp); // ... (continue for minutes, seconds, and fractional seconds)</code>
Alternatively, the "date" library offers a simplified and versatile approach:
<code class="cpp">#include "date.h" auto tp = std::chrono::system_clock::now(); auto dp = date::floor<date::days>(tp); auto ymd = date::year_month_day{dp}; auto time = date::make_time(std::chrono::duration_cast<std::chrono::milliseconds>(tp-dp)); int year = ymd.year(); int month = ymd.month(); // ... (continue for day, hour, minute, second, millisecond)</code>
The above is the detailed content of How do you extract specific temporal units from a chrono::time_point in C ?. For more information, please follow other related articles on the PHP Chinese website!