Test if string represents "yyyy-mm-dd"

2.1k Views Asked by At

I am working on a program that takes two command line arguments. Both arguments should be dates of the form yyyy-mm-dd. Since other folks will be using this program and it will be requesting from mysql, I want to make sure that the command line arguments are valid. My original thought was to loop over each element of the incoming string and perform some kind of test on it. The '-' would be easy to check but I'm not so sure how to handle the digits, and to distinguish them between ints and chars. Also, I need the first date to be "less than or equal to" the second but I'm pretty sure I can handle that.

1

There are 1 best solutions below

0
On BEST ANSWER

If you can use boost library you could simple do it like this:

string date("2015-11-12");
string format("%Y-%m-%d");
date parsedDate = parser.parse_date(date, format, svp);

You can read more about this here.

If you want a pure C++ solution you can try using

struct tm tm;   
std::string s("2015-11-123");
if (strptime(s.c_str(), "%Y-%m-%d", &tm))
    std::cout << "Validate date" << std::endl;
else
    std::cout << "Invalid date" << std::endl;

Additionally you can do a simple check to see if the date is valid, and is not for example 2351-20-35. A simple solution would be:

bool isleapyear(unsigned short year){
    return (!(year%4) && (year%100) || !(year%400));
}

//1 valid, 0 invalid
bool valid_date(unsigned short year,unsigned short month,unsigned short day){
    unsigned short monthlen[]={31,28,31,30,31,30,31,31,30,31,30,31};
    if (!year || !month || !day || month>12)
        return 0;
    if (isleapyear(year) && month==2)
        monthlen[1]++;
    if (day>monthlen[month-1])
        return 0;
    return 1;
}

Source: http://www.cplusplus.com/forum/general/3094/