Comparing 2 dates in c++

后端 未结 4 2110
独厮守ぢ
独厮守ぢ 2020-12-17 02:43

I was wondering if there is any relatively easy and short date comparison functions in C++. My dates are of type char*, and have the following format: DD

4条回答
  •  情深已故
    2020-12-17 02:56

    Parsing is usually done on streams, not strings, but you can use a stringstream.

    std::istringstream date_s( "04\\10\\1984" );
    struct tm date_c;
    date_s >> std::get_time( &date_c, "%d\\%m\\%Y" );
    std::time_t seconds = std::mktime( & date_c );
    

    Now you can compare seconds using < to determine which was earlier.

    Note, std::get_time is new in C++11. It is defined in terms of strptime, which is from POSIX but not part of the C99 standard. You can use strptime if a C++11 library is not available. If you're brave, you can also use the std::time_get facet… it's ugly though.

    If you don't want to know anything about the dates other than which is earlier, you can use std::lexicographical_compare. It would be a one-liner but the function name is so long.

    // return true if the date string at lhs is earlier than rhs
    bool date_less_ddmmyyyy( char const *lhs, char const *rhs ) {
        // compare year
        if ( std::lexicographical_compare( lhs + 6, lhs + 10, rhs + 6, rhs + 10 ) )
            return true;
        if ( ! std::equal( lhs + 6, lhs + 10, rhs + 6 ) )
            return false;
        // if years equal, compare month
        if ( std::lexicographical_compare( lhs + 3, lhs + 5, rhs + 3, rhs + 5 ) )
            return true;
        if ( ! std::equal( lhs + 3, lhs + 5, rhs + 3 ) )
            return false;
        // if months equal, compare days
        return std::lexicographical_compare( lhs, lhs + 2, rhs, rhs+2 );
    }
    

    See also how to convert datetime to unix timestamp in c? .

提交回复
热议问题