c++ - 为什么 mktime() 会更改我的 tm 结构的年份?

标签 c++ mktime

我读了两个字符串,分别是年份、儒略日(年日)、小时、分钟和观测值。

我使用 sscanf 提取相关变量:

sscanf(tide_str1.c_str(), "%d %d %d %d %Lf", &y1, &j1, &h1, &m1, &obs1);
sscanf(tide_str2.c_str(), "%d %d %d %d %Lf", &y2, &j2, &h2, &m2, &obs2);

对于这个特定的数据集,值为 2011 083 23 22 1.1

然后我创建并填充一个 tm 结构,并运行 mktime,在这期间调用 cout,它从 083 变为 364。

int y1=2011, j1=83, h1=23, m1=22;
struct tm time_struct = {0, 0, 0, 0, 0, 0, 0, 0, 0}, *time_ptr = &time_struct;
time_t tv_min;
time_struct.tm_year = y1 - 1900;
time_struct.tm_yday = j1;
cout << time_struct.tm_yday << endl;
time_struct.tm_hour = h1;
time_struct.tm_min = m1;
time_struct.tm_isdst = -1;
cout << time_struct.tm_yday << endl;
tv_min = mktime(time_ptr);
cout << time_struct.tm_yday << endl;

这是为什么呢?是因为 tm_mday 和 tm_mon 都设置为 0 了吗?我最初尝试不将其全部初始化为零,但随后 mktime 返回了 -1。如果我只知道年日而不知道月和月日,我应该采取哪些不同的做法?

最佳答案

mktime() 正在做它应该做的事情。

引用C标准:

The mktime function converts the broken-down time, expressed as local time, in the structure pointed to by timeptr into a calendar time value with the same encoding as that of the values returned by the time function. The original values of the tm_wday and tm_yday components of the structure are ignored, and the original values of the other components are not restricted to the ranges indicated above. On successful completion, the values of the tm_wday and tm_yday components of the structure are set appropriately, and the other components are set to represent the specified calendar time, but with their values forced to the ranges indicated above; the final value of tm_mday is not set until tm_mon and tm_year are determined.

mktime() 可以计算来自其他成员的tm_mdaytm_yday 的值;它不是为了计算这些字段中其他成员的值而设计的。

不过,您可以用超出范围的值初始化一个 struct tm。例如,如果您希望 tm_yday 为 200(一年中的第 200 天),您可以初始化一个表示一月第 200 天的 struct tmmktime() 然后会将其规范化为正确的日期,生成一个 time_t 值,然后您可以将该值提供给 gmtime()本地时间()

这是一个简单的例子:

#include <iostream>
#include <ctime>

int main()
{
    struct tm t = { 0 };
    t.tm_sec = t.tm_min = t.tm_hour = 0; // midnight
    t.tm_mon = 0;                        // January
    t.tm_year = 2012 - 1900;
    t.tm_isdst = -1;                     // unknown

    t.tm_mday = 200;                     // January 200th?

    time_t when = mktime(&t);
    const struct tm *norm = localtime(&when);   // Normalized time

    std::cout << "month=" << norm->tm_mon << ", day=" << norm->tm_mday << "\n";
    std::cout << "The 200th day of 2012 starts " << asctime(norm);
}

输出是:

month=6, day=18
The 200th day of 2012 starts Wed Jul 18 00:00:00 2012

关于c++ - 为什么 mktime() 会更改我的 tm 结构的年份?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9575131/

相关文章:

c++ - "no matching function call..."这个错误是从哪里来的,我该如何解决?

c++ - boost make_shared 不带模板参数

c++ - 具有继承内存存储的对象

c - mktime 返回错误的时间戳(关闭整整一个月)

c - 奇怪的 mktime() 行为

C++ 数组循环问题仍然需要帮助

c++ - DLL中静态变量的状态

Python 在 if 语句中不按 time.mktime 条件执行

date - 在awk中使用mktime时如何保留毫秒信息?

c++ - 确定 strftime char 数组的最大大小的智能方法是什么?