mktime只处理闰年? [英] mktime Only Handling Leap Years on Clang?
问题描述
在此答案中,我提议 marihikari 使用 的标准功能,
In this answer I proposed that marihikari use the standard functionality of mktime
rather than trying to implement his own Gregorian calendar system.
我写了这个函数来演示如何 mktime
可用于完成此操作:
I wrote this function to demonstrate how mktime
could be used to accomplish this:
bool leap_year(int year) {
tm bar = { 0, 0, 0, 29, 1, year - 1900 };
mktime(&bar);
return bar.tm_mday == 29 && bar.tm_mon == 1 && bar.tm_year == year - 1900;
}
使用以下方式测试:
cout << "2000: " << leap_year(2000) << "\n2001: " << leap_year(2001) << "\n2004: " << leap_year(2004) << "\n1900: " << leap_year(1900) << "\n2100: " << leap_year(2100) << endl;
在 Clang 3.7.0 :
2000:1
2001:0
2004:1
1900:0
2100:0
2000: 1
2001: 0
2004: 1
1900: 0
2100: 0
但在 gcc 5.1.0 中出现错误的结果:
But an incorrect result in gcc 5.1.0:
2000:1
2001:0
2004:1
1900:1
2100:1
2000: 1
2001: 0
2004: 1
1900: 1
2100: 1
并且 Visual Studio 2015 :
2000:1
2001:0
2004:1
1900:1
2100:0
2000: 1
2001: 0
2004: 1
1900: 1
2100: 0
我假设这是gcc 5.1.0和Visual Studio 2015中的错误?
I assume this is a bug in gcc 5.1.0 and Visual Studio 2015?
推荐答案
mktime
:
将本地日历时间转换为自纪元以来的时间a
time_t
对象。将忽略time-> tm_wday
和time-> tm_yday
。时间值允许超出正常范围。
...
如果转换成功,时间对象将被修改。
Converts local calendar time to a time since epoch as a
time_t
object.time->tm_wday
andtime->tm_yday
are ignored. The values in time are permitted to be outside their normal ranges.
...
If the conversion is successful, the time object is modified. All fields of time are updated to fit their proper ranges.
mktime
会将所有时间范围更新为适当的范围。 return:
mktime
will return:
成功后的时间自成为
time_t
时间不能表示为time_t
对象。
Time since epoch as a
time_t
object on success or -1 if time cannot be represented as atime_t
object.
实现必须做出什么努力来转换 tm
。因此只要时间被转换或 static_cast< time_t>( - 1)
/ code>已填写。
It is not specified however what efforts the implementation must make to convert the tm
. So as long as the time is converted or static_cast<time_t>(-1)
is returned the requirements for mktime
have been filled.
意味着以下函数将在所有平台上正确支持 mktime
:
bool leap_year(int year) {
tm bar = { 0, 0, 0, 29, 1, year - 1900 };
return static_cast<time_t>(-1) != mktime(&bar) && bar.tm_mday == 29 && bar.tm_mon == 1 && bar.tm_year == year - 1900;
}
这篇关于mktime只处理闰年?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!