从日期添加或减去天数的算法?

bco*_*lan 20 c++ algorithm add subtraction days

我正在尝试编写一个Date类来尝试学习C++.

我正在尝试找到一个算法来添加或减去日期到日期,其中Day从1开始,Month从1开始.它被证明是非常复杂的,并且谷歌没有出现太多,

有谁知道这样做的算法?

Mar*_*som 19

最简单的方法是实际编写两个函数,一个将日期转换为给定开始日期的天数,然后另一个函数转换回日期.一旦日期表示为天数,添加或减去日期是微不足道的.

你可以在这里找到算法:http://alcor.concordia.ca/~gpkatch/gdate-algorithm.html


Cli*_*ord 13

你真的不需要算法(至少不是名副其实的东西),标准库可以完成大部分繁重的工作; 日历计算是非常棘手的.只要您不需要早于1900年的日期,那么:

#include <ctime>

// Adjust date by a number of days +/-
void DatePlusDays( struct tm* date, int days )
{
    const time_t ONE_DAY = 24 * 60 * 60 ;

    // Seconds since start of epoch
    time_t date_seconds = mktime( date ) + (days * ONE_DAY) ;

    // Update caller's date
    // Use localtime because mktime converts to UTC so may change date
    *date = *localtime( &date_seconds ) ; ;
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

#include <iostream>

int main()
{
    struct tm date = { 0, 0, 12 } ;  // nominal time midday (arbitrary).
    int year = 2010 ;
    int month = 2 ;  // February
    int day = 26 ;   // 26th

    // Set up the date structure
    date.tm_year = year - 1900 ;
    date.tm_mon = month - 1 ;  // note: zero indexed
    date.tm_mday = day ;       // note: not zero indexed

    // Date, less 100 days
    DatePlusDays( &date, -100 ) ; 

    // Show time/date using default formatting
    std::cout << asctime( &date ) << std::endl ;
}
Run Code Online (Sandbox Code Playgroud)