确定日期的C++函数

C++ function that determines the date

本文关键字:C++ 函数 日期      更新时间:2023-10-16

我正在尝试编写一个计算租金账单的程序。我已经编写了大部分程序,但我必须编写一个函数,根据用户输入的租赁天数和开始租赁日期来确定归还日期。唯一的要求是该函数是一个调用另一个函数(决定一个月中的天数)的循环。我一直遇到的问题是,另一个函数(即确定每个月的天数)不会因月份而异。因此,如果我输入2013年1月1日,它有正确的月份天数,然后当计数器变为2月时,它将继续31天。有人知道能满足要求的配方吗?

从一个带有每个月天数的硬编码数组开始。补偿二月的闰日,你应该是好的。

int daysInMonth(int month, int year)
{
    // Check for leap year
    bool isLeapYear;
    if (year % 400 == 0)
        isLeapYear = true;
    else if (year % 4 == 0 && year % 100 != 0)
        isLeapYear = true;
    else
        isLeapYear = false;
    int numDaysInMonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
    if (isLeapYear)
        numDaysInMonth[1]++;
    return numDaysInMonth[month - 1];
}

为什么不考虑使用Boost.Date_Time?

int isLeap(int year)
{ 
    return (year > 0) && !(year % 4) && ((year % 100) || !(year % 400));
}
int calcDays(int month, int year)
{
    static const int daysInMonth[2][13] = {
        { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
        { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } };
    if (month >= 1 && month <= 12) {
        return daysInMonth[isLeap(year)][month - 1];
    }
    return -1;
}

这将为您提供一个月中的天数