Algorithm to add or subtract days from a date?

后端 未结 10 1238
野的像风
野的像风 2020-12-01 14:10

I\'m trying to write a Date class in an attempt to learn C++.

I\'m trying to find an algorithm to add or subtract days to a date, where Day starts from 1 and Month s

10条回答
  •  感动是毒
    2020-12-01 14:44

    Here's a sketch of a very simple approach. For simplicity of ideas I will assume that d, the number of days to add, is positive. It is easy to extend the below to cases where d is negative.

    Either d is less than 365 or d is greater than or equal to 365.

    If d is less than 365:

    m = 1;
    while(d > numberOfDaysInMonth(m, y)) {
        d -= numberOfDaysInMonth(m, y);
        m++;
    }
    return date with year = y, month = m, day = d;
    

    If d is greater than 365:

    while(d >= 365) {
        d -= 365;
        if(isLeapYear(y)) {
            d -= 1;
        }
        y++;
    }
    // now use the case where d is less than 365
    

    Alternatively, you could express the date in, say, Julian form and then merely add to the Julian form and conver to ymd format.

提交回复
热议问题