Meysam
Meysam

Reputation: 18137

How to validate input string in short time format

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?

Upvotes: 1

Views: 1550

Answers (3)

MojaveWastelander
MojaveWastelander

Reputation: 66

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;
    

Upvotes: 2

suszterpatt
suszterpatt

Reputation: 8273

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.

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249293

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

Upvotes: 2

Related Questions