c++ - mktime 仅处理 Clang 上的闰年?

标签 c++ visual-studio gcc clang mktime

this answer我提议 marihikari使用 mktime 的标准功能而不是尝试实现他自己的公历系统。

我编写这个函数是为了演示如何使用 mktime 来完成此任务:

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

但是 gcc 5.1.0 中的结果不正确:

2000: 1
2001: 0
2004: 1
1900: 1
2100: 1

Visual Studio 2015 中的结果不正确:

2000: 1
2001: 0
2004: 1
1900: 1
2100: 0

我认为这是 gcc 5.1.0 和 Visual Studio 2015 中的错误?

最佳答案

mktime :

Converts local calendar time to a time since epoch as a time_t object. time->tm_wday and time->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将返回:

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

但未指定实现必须做出哪些努力才能转换 tm .所以只要转换时间或者static_cast<time_t>(-1)返回 mktime 的要求已满。

意思是下面的函数will work on all platforms正确支持 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;
}

关于c++ - mktime 仅处理 Clang 上的闰年?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33477379/

相关文章:

c++ - 如何在派生类构造函数中初始化基类成员变量?

c++ - 如何在 VS2008 中指定 64 位 unsigned int const 0x8000000000000000?

c# - 调试序列化期间消耗的 yield 返回的最佳方法?

c - 为什么 __sync_add_and_fetch 在 32 位系统上对 64 位变量起作用?

c++ - Directx C++ - 绘制 DNA 形状

c++ - 在初始化对象上调用虚方法的段错误

c++ - 为什么固定宽度无符号整数的输出为负,而无符号整数输出按预期回绕?

visual-studio - 如何使 Visual Studio 编辑器停止滚动到文件底部?

c++ - G++ 让我调用未定义的方法

linux - show 的 nm 输出共享库的版本不正确