使用 gmtime() 获取正确的人的生活期限

问题描述

我正在尝试使用现在和出生日期之间的差异来计算人的确切年龄。我得到了几秒钟的差异,我认为这是正确的值。然后我想使用 struct tm 将秒数转换为 gmtime()。但它在 70 上给了我一个 tm_year 比它必须大,而 tm_mday 在 1 上比必须大。 tm_mday 似乎很清楚-它的范围是从 1 到 31,我可以从中减去 1,而 tm_year 是从 1900 年开始的年份。好吧,那么为什么 {{1} } 给我 +70 年?

gmtime()@H_404_17@

}

输出

#include <iostream>
#include <ctime>
using namespace std;

int main() {
int min,h,d,m,y;
struct tm bd = {0};
cout << "Enter birth date in the format: hh:min/dd.mm.yyyy"<<endl;
scanf("%d:%d/%d.%d.%d",&h,&min,&d,&m,&y);
bd.tm_year = y-1900;
bd.tm_mon = m-1;
bd.tm_mday = d;
bd.tm_hour = h;
bd.tm_min = min;

time_t Now = time(NULL);
cout << "Now: "<<Now<<" BD: "<<mktime(&bd)<<endl;
time_t seconds = difftime(Now,mktime(&bd));//(end,beginning)
cout <<"seconds elapsed: "<< seconds<<endl;
struct tm * age;
age = gmtime (&seconds);
cout << "year" << age->tm_year << endl;
cout << "mon" << age->tm_mon << endl;
cout << "mday" << age->tm_mday << endl;
cout << "hour" << age->tm_hour << endl;
cout << "min" << age->tm_min << endl;
cout << "sec" << age->tm_sec << endl;
@H_404_17@


解决方法

它将“unix epoch time”(自 1970 年以来的秒数)转换为日期。

它不会将秒转换为天/月/年。基本上没有这种转换。 30 天可以少于或多于一个月。 365 天可以是一年,也可以是不到一年的 1 天。 24 次 60 次 60 秒可能不到闰秒发生的一天。

时间点后的秒数是日期。但秒不会唯一地映射到天数/月数/年数。

找到两个时间点 - 日期 - 并比较/减去组件来做到这一点。