c++ - 使用 <ctime> mktime 的有效日期函数

标签 c++ date mktime ctime

我想要一个接受日、月、年三个输入并告诉我它是否有效的函数。然后使用 http://www.cplusplus.com/reference/ctime/mktime/ 上的示例

我尝试实现我的功能:

bool ValidDate(int d, int m, int y)
{
struct tm *timeinfo;
time_t rawtime;
time (&rawtime);
timeinfo = localtime(&rawtime);
timeinfo->tm_year = y - 1900;
timeinfo->tm_mon = m - 1;
timeinfo->tm_mday = d;

if (mktime(timeinfo) == -1 )
    return false;
else return true;
}

问题是函数返回的不是我想要的。 例如我正在检查

if (ValidDate(4,13,2010)) // out put is valid
    std::cout << "valid\n";
else std::cout << "Invalid\n";

ValidDate(4,22,2010) // valid
ValidDate(344,13,2010) //valid
ValidDate(4,133,2010) //valid
ValidDate(31,12, 1920) //invalid
ValidDate(31,9,2010) //valid
ValidDate(4,9,2010) //valid

为什么?谢谢。 编辑: 除了 31、12、1920 和 4、9、2010 之外,所有输入的日期均无效,并且没有一个输出是正确的。

最佳答案

mktime返回如下:

Time since epoch as a std::time_t object on success or -1 if time cannot be represented as a std::time_t object.

std::time_t定义如下:

Arithmetic type capable of representing times.

Although not defined, this is almost always a integral value holding the number of seconds (not counting leap seconds) since 00:00, Jan 1 1970 UTC, corresponding to POSIX time.

因此 31/12/1920 不能表示为 std::time_t,因为它在纪元之前。


至于报告为有效的其他无效日期,mktime 还指出:

The values in [the parameter] are permitted to be outside their normal ranges.

这是取自 cppreference 的示例:

#include <iostream>
#include <iomanip>
#include <ctime>

int main()
{
    std::time_t t = std::time(NULL);
    std::tm tm = *std::localtime(&t);
    std::cout << "Today is           " << std::put_time(&tm, "%c %Z") <<'\n';
    tm.tm_mon -= 100;  // tm_mon is now outside its normal range
    std::mktime(&tm);
    std::cout << "100 months ago was " << std::put_time(&tm, "%c %Z") << '\n';
}

输出是:

Today is Wed Dec 28 09:56:10 2011 EST
100 months ago was Thu Aug 28 10:56:10 2003 EDT

关于c++ - 使用 <ctime> mktime 的有效日期函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23433324/

相关文章:

c++ - 修改按值传递的参数对调用者的变量没有影响

如果类的成员,C++ 数组会导致崩溃

php - 将 Javascript 日期字符串转换为 PHP 日期

python - 曲线拟合到格式为 'datetime' 的时间序列?

c - c mktime 在 Windows 和 GNU/Linux 上是否不同?

c++ - 如何在nodejs中使用C++ api?

c++ - dynamic_cast 的用例

php - 比较有问题的php中的日期

java - 解析西类牙语日期错误

valgrind 提示 __mktime - 那是我的错吗?