[英]C struct tm time - add hours
I have struct tm
that represents time 1900-01-01 00:00:00
.我有
struct tm
代表时间1900-01-01 00:00:00
。 How can I add offset in hours to it?如何在小时内添加偏移量? For example, I have offset in hours - value
1048621
(aprox. 119.7 years).例如,我的时间偏移量为
1048621
(大约 119.7 年)。
Assuming the resulting date/time falls into the range representable by time_t
, you can add the hours offset to tm::tm_hour
then call mktime
to normalize.假设生成的日期/时间落入
time_t
可表示的范围内,您可以将小时偏移量添加到tm::tm_hour
然后调用mktime
进行规范化。
#include <time.h>
#include <stdio.h>
int main()
{
struct tm t = { 0 };
t.tm_mday = 1; // Jan 1st 1900
t.tm_hour = 1048621;
if(mktime(&t) == -1) return 1;
printf("%d-%02d-%02d %02d:%02d:%02d\n",
t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
t.tm_hour, t.tm_min, t.tm_sec);
return 0;
}
2019-08-17 13:00:00
[ EDIT ] As pointed out in a comment, the above mktime
call fails with MSVC. [编辑] 正如评论中所指出的,上述
mktime
调用因 MSVC 而失败。 Turns out that Microsoft's mktime
implementation does a precheck on the tm
argument, and unconditionally fails if tm_year < 69
before/without even looking at the other tm
fields.事实证明,微软的
mktime
实现对tm
参数进行了预检查,如果tm_year < 69
之前/甚至不查看其他tm
字段,则无条件失败。 While it is expected for mktime
to fail if the end date/time falls outside the time_t
range, in particular if it is earlier than the start of the epoch (usually Jan 1st 1970), such check should normally be done after (re)normalization.虽然如果结束日期/时间超出
time_t
范围,预计mktime
会失败,特别是如果它早于纪元的开始(通常是 1970 年 1 月 1 日),但通常应该在(重新)规范化之后进行此类检查.
Below is updated code that adds range validation, and was verified to work with gcc and msvc .下面是添加范围验证的更新代码,并已验证可与gcc和msvc一起使用。
#include <time.h>
#include <limits.h>
#include <stdio.h>
int main()
{
const int tmYear1970 = 70;
const int tmDay1970 = tmYear1970 * 365 + tmYear1970 / 4; // 25568
const int tmHour1970 = tmDay1970 * 24; // 613632
const int tmHourMax = INT_MAX - tmHour1970; // 2146870015
int tmHour = 1048621;
if(tmHour < tmHour1970 || tmHour > tmHourMax) return 2;
struct tm t = { 0 };
t.tm_mday = 1; // Jan 1st 1900 12 AM
t.tm_year = tmYear1970;
t.tm_hour = tmHour - tmHour1970;
t.tm_isdst = -1;
if (mktime(&t) == -1) return 1;
printf("%d-%02d-%02d %02d:%02d:%02d\n",
t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
t.tm_hour, t.tm_min, t.tm_sec);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.