Question

I've got an input string which is to represent a 24h time. Valid inputs are strings like:

7:04
07:4
7:4
07:04

And an invalid input string would be obviously something like 25:68. Is there any easy way to validate the time format, and then parse the time in epoch format given that the time is of today? Is there possibly any boost library that comes handy here?

Was it helpful?

Solution

You can do it using strptime, which is standard on Unix-like systems: http://www.kernel.org/doc/man-pages/online/pages/man3/strptime.3.html

OTHER TIPS

I see two options:

  1. Simple regex or boost::xpressive (I like it more).

  2. Get the numbers between semicolon and convert them to numbers, then check their values. Something like this:

    string sTime("53:30");
    int iSemiColon = sTime.find(':');       
    if (atoi(sTime.substr(0, iSemiColon).c_str()) >= 24) return false;
    if (atoi(sTime.substr(iSemiColon + 1).c_str()) >= 60) return false;
    

See this answer. If you're not limited to STL, you could use boost.Regex for the validation part, though it's such a simple problem that you could easily roll your own solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top