gpt4 book ai didi

c++ - 将天数添加到日期 C++

转载 作者:行者123 更新时间:2023-11-28 05:53:03 27 4
gpt4 key购买 nike

我正在尝试为日期添加一定天数。我看过诸如 Arithmetics on calendar dates in C or C++ (add N days to given date) 之类的示例, 但我仍然遇到这个问题。

如果 num_of_days 是一个很大的数字,比如 100,开始日期是 expire_time.tm_mday = 10。最后一天是 110。所以当我做 mktime(&expire_time);它不会将这一天转换为有效时间; expire_time.tm_mday 仍然等于 110。我希望它在 3 个月后加上 1-31 之间的一天。这是为什么?

void add_num_of_days(int* month, int* day, int* year, int num_of_days) 
{
struct tm expire_time = {};
int date_to_days;
expire_time.tm_year = *year - 1900;
expire_time.tm_mon = *month - 1;
expire_time.tm_mday = *day;

//expire_time.tm_mday = 15;
//num_of_days = 40;
expire_time.tm_mday += num_of_days;

mktime(&expire_time);

//expire_time.tm_mday = 55! (NOT WHAT I WANT).
*day = expire_time.tm_mday;
*month = expire_time.tm_mon + 1;
*year = expire_time.tm_year + 1900;
}

调用代码:

month1 = atoi(start_date.Mid(0, 2)) + 1;
day1 = atoi(start_date.Mid(2, 2));
year1 = atoi(start_date.Mid(4)) + 1900;
//Add the number of days the license
//period is for to the start date.
add_num_of_days(&month1, &day1, &year1, atoi(num_of_days));

开始日期:

//First 32 bits is for the starting date.
CString start_date = get_start_date(byte_array.Mid(0, 32));
//Example start_date would be 01152016 for Jan 15th 2016.

最佳答案

您没有检查 mktime(&expire_time); 的返回值。根据 documentation,如果无法表示日历时间,它返回 -1,因此在这种情况下,您的输入参数不变。

为避免此类问题,您可以将程序更改为:

bool add_num_of_days(int* month, int* day, int* year, int num_of_days) 
{
struct tm expire_time = {};
int date_to_days;
expire_time.tm_year = *year - 1900;
expire_time.tm_mon = *month - 1;
expire_time.tm_mday = *day;

expire_time.tm_mday += num_of_days;

if (-1 == mktime(&expire_time))
{
return false;
}

*day = expire_time.tm_mday;
*month = expire_time.tm_mon + 1;
*year = expire_time.tm_year + 1900;
return true;
}

然后在调用时检查函数的返回值。


而且,现在让我们了解 为什么 mktime 说它无法转换您的日期的原因。

当您使用 01152016 作为输入日期时,日期中的年份为 2016。但是,当您从字符串转换为 int 时,您会向它添加额外的 1900 (year1 = atoi(start_date.Mid(4)) + 1900;),使日期等于 3916。显然,这比 mktime 可以处理的 future 太远(我的猜测是,它不能在 time_t 的大小限制内表示您的日期)。

请注意,即使您在函数中减去年份 1900,对于 mktime 来说,年份仍然等于 3916,因为 tm.tm_year 是定义为“自 1900 年以来的年数”,因此当 1900 年之后有 2016 年时,它仍然等于 3916。

关于c++ - 将天数添加到日期 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34814093/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com