为什么 mktime 为我的 std::tm 返回 -1 [英] Why is mktime returning -1 for my std::tm

查看:65
本文介绍了为什么 mktime 为我的 std::tm 返回 -1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来正确的 std::tm.

I have a std::tm that looks correct.

但是,当使用 mktime 规范化时,我看到的是 -1

However when normalizing with mktime I am seeing a -1

根据man mktime:

mktime() 函数返回指定的日历时间;如果不能表示日历时间,则返回-1;

但是,查看我发布的屏幕截图,我看不出 std::tm 中的内容有什么问题 tm_gmtofftm_zone?

However, looking at the screenshot I posted, I dont see what is wrong with what is being put in the std::tm Is there a problem with tm_gmtoff and tm_zone?

推荐答案

struct tm 对象的 tm_year 成员表示自 1900 年以来的年份,而不是年份编号.将tm_year设置为2014是指3914年,可能在time_t的范围之外.在许多系统上,time_t 值是一个有符号的 32 位整数,表示自 1970-01-01 00:00:00 UTC 以来的秒数,该值在 2038 年溢出.

The tm_year member of a struct tm object denotes years since 1900, not the year number. Setting tm_year to 2014 refers to the year 3914, which is likely outside the range of time_t. On many systems, a time_t value is a signed 32-bit integer representing seconds since 1970-01-01 00:00:00 UTC, which overflows in the year 2038.

这是历史原因.当这个接口被发明时,年份是用 2 位数字存储的,因为这在当时似乎是合理的做法.后来更新为能够一致地引用 1999 年之后的年份,但在不破坏现有代码的情况下更改现有值是不可能的.

The reasons for this are historical. When this interface was invented, years were stored using 2 digits, because that seemed to be the reasonable thing to do at the time. It was later updated to be able to refer to years after 1999 consistently, but it wasn't possible to change existing values without breaking existing code.

需要注意的其他事项:tm_mon 成员将一月编码为 0,将十二月编码为 11;这便于用作月份名称数组的索引.您示例中的 tm_mon 值 5 指的是六月,而不是五月.

Something else to watch out for: the tm_mon member encodes January as 0 and December as 11; this is convenient for use as an index into an array of month names. The tm_mon value of 5 in your example refers to June, not May.

tm_gmtofftm_zone 成员是非标准的;它们特定于您的实现.允许实现向 struct tm 添加其他成员,但您应该知道列表中只有前 9 个成员是标准的;依赖于任何其他代码的代码将不可移植.

The tm_gmtoff and tm_zone members are non-standard; they're specific to your implementation. Implementations are permitted to add additional members to struct tm, but you should be aware only first 9 members in your list are standard; code that depends on any of the others will not be portable.

这篇关于为什么 mktime 为我的 std::tm 返回 -1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆