C++ check if a date is valid

前端 未结 3 1374
自闭症患者
自闭症患者 2021-02-15 14:48

is there any function to check if a given date is valid or not? I don\'t want to write anything from scratch.

e.g. 32/10/2012 is not valid and 10/10/2010 is valid

相关标签:
3条回答
  • 2021-02-15 15:22

    The boost date time class should be able to handle what you require. See http://www.boost.org/doc/libs/release/doc/html/date_time.html

    0 讨论(0)
  • 2021-02-15 15:29

    If the format of the date is constant and you don't want to use boost, you can always use strptime, defined in the ctime header:

    const char date1[] = "32/10/2012";
    const char date2[] = "10/10/2012";
    struct tm tm;
    
    if (!strptime(date1, "%d/%m/%Y", &tm)) std::cout << "date1 isn't valid\n";
    if (!strptime(date2, "%d/%m/%Y", &tm)) std::cout << "date2 isn't valid\n";
    
    0 讨论(0)
  • 2021-02-15 15:31

    If your string is always in that format the easiest thing to do would be to split the string into its three components, populate a tm structure and pass it to mktime(). If it returns -1 then it's not a valid date.

    You could also use Boost.Date_Time to parse it:

    string inp("10/10/2010");
    string format("%d/%m/%Y");
    date d;
    d = parser.parse_date(inp, format, svp);
    
    0 讨论(0)
提交回复
热议问题