gpt4 book ai didi

c++ - 比较C++中的2个日期

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:19:25 30 4
gpt4 key购买 nike

我想知道C++中有没有比较简单和简短的日期比较函数。我的日期是 char* 类型,格式如下:DD\MM\YYYY

谢谢。

最佳答案

解析通常在流上完成,而不是字符串,但您可以使用 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 );

现在您可以使用 < 来比较秒数以确定哪个更早。

请注意, std::get_time 在 C++11 中是新的。它是根据 strptime 定义的,它来自 POSIX 但不是 C99 标准的一部分。您可以使用 strptime 如果 C++11 库不可用。如果你够勇敢,你也可以使用 std::time_get小平面……虽然很丑。

如果除了更早的日期之外你不想知道任何关于日期的信息,你可以使用std::lexicographical_compare。 .这将是一行,但函数名称太长了。

// 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 );
}

另见 how to convert datetime to unix timestamp in c? .

关于c++ - 比较C++中的2个日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13787702/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com