A possible solution can also be based on strptime , however, note that this function only checks if the day is from the interval <1;31> and the month is from <1;12> , i.e. "30/02/2013" remains valid:
#include <iostream> #include <ctime> int main() { struct tm tm; std::string s("32/02/2013"); if (strptime(s.c_str(), "%d/%m/%Y", &tm)) std::cout << "date is valid" << std::endl; else std::cout << "date is invalid" << std::endl; }
But since
strptime not always available, and an extra check would be nice, here is what you could do:
- extraction day, month, year
- fill in
struct tm - normalize him
- check if the normalized date is still the same as for the day, month, year.
i.e:.
#include <iostream>
used as:
int main() { std::string s("29/02/2013"); int d,m,y; if (extractDate(s, d, m, y)) std::cout << "date " << d << "/" << m << "/" << y << " is valid" << std::endl; else std::cout << "date is invalid" << std::endl; }
which in this case would date is invalid , since normalization would detect that 29/02/2013 was normalized on 01/03/2013 .
Liho
source share