关于std::chrono中system_clock::now()无法转换为sys_days的技术咨询
system_clock::now() to sys_days Hey there! Let's tackle your two chrono-related questions clearly and directly.
Why Direct Assignment Fails
First, your confusion about why std::chrono::sys_days sd = n; throws an error makes total sense—both are time_point types, but their duration units are wildly different:
std::chrono::system_clock::now()returns atime_point<system_clock, system_clock::duration>, which uses a fine-grained unit like nanoseconds or microseconds (depends on your system).sys_daysis an alias fortime_point<system_clock, days>, which uses whole days as its base unit.
C++ doesn't allow implicit conversion between these because it would require truncating or rounding fine-grained time down to whole days—and the compiler can't guess whether you want to floor, ceil, or round the value. This is a safety feature to prevent accidental precision loss.
How to Get the Current Date with now()
To convert system_clock::now() to sys_days correctly, you need to explicitly choose how to handle the time-to-day conversion using chrono's rounding functions:
floor<days>(tp): Truncates to the start of the current day (most common for "current date" use cases)ceil<days>(tp): Rounds up to the next day if the time is past midnightround<days>(tp): Rounds to the nearest day based on the time (e.g., 12:00 noon would round up)
Here's the working code for getting the current date:
#include <chrono> #include <iostream> int main() { // Get current system time auto now = std::chrono::system_clock::now(); // Convert to sys_days using floor to get the start of today std::chrono::sys_days today = std::chrono::floor<std::chrono::days>(now); // Optional: Convert to human-readable year/month/day std::chrono::year_month_day ymd = today; std::cout << "Current date: " << ymd.year() << "-" << ymd.month() << "-" << ymd.day() << "\n"; return 0; }
This code safely converts the fine-grained time point to a day-aligned time point, giving you the current calendar date.
内容的提问来源于stack exchange,提问作者Juan Dent

