如何比较C或C++中的日/月/年?

use*_*026 2 c c++ comparison date

我有一个程序,要求用户输入日期然后它显示哪一个是最近我已经这样做了

if (year1>year2 || month1>month2 || day1>day2)
    return -1;

if (year1<year2 || month1<month2 || day1<day2)
    return +1;
Run Code Online (Sandbox Code Playgroud)

但输出不太正确.

jua*_*nza 8

这是一个干净的方法:

#include <tuple> // for std::tie

auto date1 = std::tie(year1, month1, day1);
auto date2 = std::tie(year2, month2, day2);

if (date1 == date2)
  return 0;

return (date1 < date2) ? -1 : 1; 
Run Code Online (Sandbox Code Playgroud)

std::tie对象的比较是词典编纂,因此-1如果date1小于date2,0如果它们相同,并且1如果date1大于,则返回date2.

您可能最好定义自己的date类型(或使用boost::datetime).

struct Date
{
  unsigned year;
  unsigned month;
  unsigned day;
};

bool operator<(const Date& lhs, const Date& rhs)
{
  return std::tie(lhs.year, lhs.month, lhs.day) < 
         std::tie(rhs.year, rhs.month, rhs.day);
}

bool operator>(const Date& lhs, const Date& rhs) { .... }

bool operator==(const Date& lhs, const Date& rhs) { .... }

int date_cmp(const Date& lhs, const Date& rhs) 
{
  // use operators above to return -1, 0, 1 accordingly
}
Run Code Online (Sandbox Code Playgroud)