Check if the string "yyyy-mm-dd" matches

I am working on a program that takes two command line arguments. Both arguments must be dates of the form yyyy-mm-dd. Since other people will be using this program and it will ask mysql, I want to make sure the command line arguments are valid. My initial thought was to iterate over every element of the incoming string and do some kind of test on it. "-" would be easy to check, but I'm not sure how to handle numbers and distinguish between ints and chars. Also, I need the first date to be "less than or equal to" the second, but I'm sure I can handle that.

+3


source to share


1 answer


If you can use the boost library, you can simply 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;

      

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

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/

+5


source







All Articles