我需要能够根据 ISO-8601 标准的子集解析和存储各种日期、时间或两者。
日期的格式如下:
时间的格式如下:
如果同时定义了日期和时间,则还必须定义时区,如下所示:
我尝试使用 Howard Hinnant 的日期库,它与 C++20 标准中的日期库相同。看来我需要使用特定类型来解析不同的格式,这有点烦人。我宁愿能够解析并存储同一类型中的任何格式。
为了说明问题:
sys_time<microseconds> sys_us;
microseconds us;
year_month ym;
year y;
std::istringstream iss;
iss.str("2012-03-04T05:06:07.123456+07:00");
iss >> date::parse("%FT%T%Ez", sys_us); // Only works with this type. (The others can't parse this much info.)
assert(!iss.fail());
iss.str("2012-03-04");
iss >> date::parse("%F", sys_us); // If the date has the full year, month, and day, this works.
assert(!iss.fail());
iss.str("2012-03");
// iss >> date::parse("%Y-%m", sys_us); // This fails; day is missing. …Run Code Online (Sandbox Code Playgroud)