Extracting Temporal Elements from an std::chrono::time_point
Query:
How can I extract specific temporal elements, such as year, month, day, hour, minute, second, and milliseconds, from an std::chrono::time_point object?
Resolution:
To extract these elements from a time_point, you must use the system_clock::time_point, as it has a relationship with the civil calendar. Retrieve the current system_clock::time_point:
<code class="cpp">system_clock::time_point now = system_clock::now();</code>
Convert this to a time_t value:
<code class="cpp">time_t tt = system_clock::to_time_t(now);</code>
If you require time extraction in the UTC timezone or local timezone, convert the time_t value to a tm:
<code class="cpp">tm utc_tm = *gmtime(&tt); // UTC tm local_tm = *localtime(&tt); // Local</code>
Extract specific elements using the corresponding fields of the tm structure:
<code class="cpp">std::cout << local_tm.tm_year + 1900 << '\n'; // Year std::cout << local_tm.tm_mon + 1 << '\n'; // Month std::cout << local_tm.tm_mday << '\n'; // Day
Expanded Information:
While using the C library allows for time conversion, it is important to note that every system_clock implementation is based on Unix time, typically measured in seconds since January 1, 1970 UTC.
For more precise extraction, take advantage of the system_clock precision:
<code class="cpp">system_clock::duration tp = now.time_since_epoch(); days d = duration_cast<days>(tp); // Days tp -= d; // Subtract days hours h = duration_cast<hours>(tp); // Hours tp -= h; // Subtract hours ... // Continue for minutes, seconds, and fractional seconds</code>
Print the results with the appropriate duration units:
<code class="cpp">std::cout << d.count() << "d " << h.count() << ':' << m.count() << ':' << s.count(); std::cout << " " << tp.count() << "[" << system_clock::duration::period::num << '/' << system_clock::duration::period::den << "]\n";
Library Enhancements:
For simplified time extraction, consider using a C 11/14 library such as date. This reduces the necessary code to:
<code class="cpp">auto tp = std::chrono::system_clock::now(); using date::floor; // Namespace for streaming operator std::cout << tp << '\n'; // Outputs date and time components auto dp = floor<date::days>(tp); // Omits fractional parts auto ymd = date::year_month_day{dp}; ... // Individual elements can be accessed as members of ymd</code>
C 20 Standard Proposal:
The proposed C 20 working draft includes direct syntax for extracting these fields from system_clock::time_point:
<code class="cpp">year_month_day ymd{floor<days>(tp)}; hh_mm_ss time{floor<milliseconds>(tp - dp)}; auto y = ymd.year(); auto m = ymd.month(); ... // Extract remaining elements similarly</code>
The above is the detailed content of How can I extract individual temporal elements like year, month, day, hour, minute, second, and milliseconds from an std::chrono::time_point object?. For more information, please follow other related articles on the PHP Chinese website!