比较c ++中的2个日期 [英] Comparing 2 dates in c++

查看:72
本文介绍了比较c ++中的2个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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\MM\YYYY

谢谢。

推荐答案

解析通常是在流,不是字符串,但可以使用 stringstream

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

现在您可以使用<

请注意, std :: get_time 是C ++ 11中的新增功能。它是根据 strptime 定义的,它来自POSIX,但不是C99标准的一部分。您可以使用 strptime 如果C ++ 11库不可用。如果你勇敢,你也可以使用 std :: time_get facet ...它很丑陋。

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.

你不想知道除了早先的日期之外的任何事情,你可以使用 std :: lexicographical_compare

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

另请参阅如何在c?中将datetime转换为unix时间戳。

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

这篇关于比较c ++中的2个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆