Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
848 views
in Technique[技术] by (71.8m points)

c++ - Parse ISO 8601 durations

In ISO 8601, durations are given in the format P[n]Y[n]M[n]DT[n]H[n]M[n]S.

Examples:

20 seconds:

PT20.0S

One year, 2 month, 3 days, 4 hours, 5 minutes, 6 seconds:

P1Y2M3DT4H5M6S

Question:

Given a string that contains a duration in iso 8601 format. I want to obtain the overall number of seconds of that duration. What is the recommended way in standard C++11 to achieve this?

Remarks:

E.g., there is ptime from_iso_string(std::string) in boost DateTime which does not fit here. Is there a similar way without doing a regex by hand?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the standard regex library, the regex you want is something like:

"P(([0-9]+)Y)?(([0-9]+)M)?(([0-9]+)D)?T(([0-9]+)H)?(([0-9]+)M)?(([0-9]+(.[0-9]+)?S)?"

from that you can pull out the number of years, months etc and calculate total seconds.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...