我想要一个接受日、月、年三个输入并告诉我它是否有效的函数。然后使用 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 astd::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/