简单的方法来添加1个月到C / C ++中的time_t [英] easy way to add 1 month to a time_t in C/C++

查看:166
本文介绍了简单的方法来添加1个月到C / C ++中的time_t的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些使用Oracle函数add_months的代码将日期增加X个月。

I have some code that uses the Oracle function add_months to increment a Date by X number of months.

我现在需要重新实现相同的逻辑C / C ++函数。因为我不想/需要进去,我不能简单地向oracle发出查询来获取新的日期。

I now need to re-implement the same logic in a C / C++ function. For reasons I don't want/need to go into I can't simply issue a query to oracle to get the new date.

有没有人知道一个简单和可靠的方式将X个月的时间添加到time_t?
计算类型的一些示例如下所示。

Does anyone know of a simple and reliable way of adding X number of months to a time_t? Some examples of the types of calculations are shown below.

30/01/2009 + 1个月= 28/02/2009

31/01/2009 + 1个月= 28/02/2009

27/02/2009 + 1个月= 27/03/2009

28/02/2009 + 1月= 31/03/2009

31/01/2009 + 50个月= 31/03/2013

30/01/2009 + 1 month = 28/02/2009
31/01/2009 + 1 month = 28/02/2009
27/02/2009 + 1 month = 27/03/2009
28/02/2009 + 1 month = 31/03/2009
31/01/2009 + 50 months = 31/03/2013

推荐答案

方法 AddMonths_OracleStyle 可以满足您的需要。

Method AddMonths_OracleStyle does what you need.

也许您可能希望将IsLeapYear和GetDaysInMonth替换为某些库管理器方法。

Perhaps you would want to replace IsLeapYear and GetDaysInMonth to some librarian methods.

#include <ctime>
#include <assert.h>

bool IsLeapYear(int year) 
{
    if (year % 4 != 0) return false;
    if (year % 400 == 0) return true;
    if (year % 100 == 0) return false;
    return true;
}

int daysInMonths[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

int GetDaysInMonth(int year, int month)
{
    assert(month >= 0);
    assert(month < 12);

    int days = daysInMonths[month];

    if (month == 1 && IsLeapYear(year)) // February of a leap year
        days += 1;

    return days;
}

tm AddMonths_OracleStyle(const tm &d, int months)
{
    bool isLastDayInMonth = d.tm_mday == GetDaysInMonth(d.tm_year, d.tm_mon);

    int year = d.tm_year + months / 12;
    int month = d.tm_mon + months % 12;

    if (month > 11)
    {
        year += 1;
        month -= 12;
    }

    int day;

    if (isLastDayInMonth)
        day = GetDaysInMonth(year, month); // Last day of month maps to last day of result month
    else
        day = std::min(d.tm_mday, GetDaysInMonth(year, month));

    tm result = tm();

    result.tm_year = year;
    result.tm_mon = month;
    result.tm_mday = day;

    result.tm_hour = d.tm_hour;
    result.tm_min = d.tm_min;
    result.tm_sec = d.tm_sec;

    return result;
}

time_t AddMonths_OracleStyle(const time_t &date, int months)
{
    tm d = tm();

    localtime_s(&d, &date);

    tm result = AddMonths_OracleStyle(d, months);

    return mktime(&result);
}

这篇关于简单的方法来添加1个月到C / C ++中的time_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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