小编use*_*045的帖子

使用 Howard Hinnant 的日期库一致地解析各种日期和时间格式

我需要能够根据 ISO-8601 标准的子集解析和存储各种日期、时间或两者。

日期的格式如下:

  • YYYY
  • YYYY-毫米
  • YYYY-月-日

时间的格式如下:

  • 时:分:秒
  • 时:分:SS.ffffff

如果同时定义了日期和时间,则还必须定义时区,如下所示:

  • YYYY-mm-ddTHH:MM:SS.ffffff+ZZ:ZZ
    • 例如:2012-03-04T05:06:07.123456+07:00

我尝试使用 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)

c++ datetime c++-chrono c++20

4
推荐指数
1
解决办法
794
查看次数

标签 统计

c++ ×1

c++-chrono ×1

c++20 ×1

datetime ×1