如何比较C++中的两个日期

How to compare two dates in C++

本文关键字:两个 日期 C++ 何比较 比较      更新时间:2023-10-16

我需要比较两个日期。用户输入 1 的当前日期,格式为 dd/mm/yyyy。

所以如果expiry_date> current_date

显示。。。。我尝试过 difftime(),但这效果不佳,因为它使用了时间参数

time_t now;
  struct tm newyear;
  double seconds;
  time(&now);  /* get current time; same as: now = time(NULL)  */
  newyear = *localtime(&now);
  newyear.tm_hour = 0; newyear.tm_min = 0; newyear.tm_sec = 0;
  newyear.tm_mon = 0;  newyear.tm_mday = 1;
  seconds = difftime(now,mktime(&newyear));
  printf ("%.f seconds diff", seconds);
  system("pause");

这是我找到的示例代码

如果这真的是一个固定的格式,你可以通过简单的C字符串比较来完成

int date_cmp(const char *d1, const char *d2)
{
    int rc;
    // compare years
    rc = strncmp(d1 + 6, d2 + 6, 4);
    if (rc != 0)
        return rc;
    // compare months
    rc = strncmp(d1 + 3, d2 + 3, 2);
    if (rc != 0)
        return rc;
    // compare days
    return strncmp(d1, d2, 2);
}

尝试 strftime 将字符串解析为 tm*,然后使用 mktime() 和 difftime()。