Arithmetics on calendar dates in C or C++ (add N days to given date)

后端 未结 8 1078
误落风尘
误落风尘 2020-12-06 07:47

I have been given a date, Which I am taking as an input like (day, month, year): 12, 03, 87.

Now I need to find out the date after n days.<

相关标签:
8条回答
  • 2020-12-06 07:57

    Can be implemented using C++ operators and in a quite OOP way by representing date as a class.

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class Date {
    public:
        Date(size_t year, size_t month, size_t day):m_year(year), m_month(month), m_day(day) {}
        ~Date() {}
    
        // Add specified number of days to date
        Date operator + (size_t days) const;
    
        size_t Year()  { return m_year; }
        size_t Month() { return m_month; }
        size_t Day()   { return m_day; }
    
        string DateStr();
    private:
        // Leap year check 
        inline bool LeapYear(int year) const
            { return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); }
    
        // Holds all max days in a general year
        static const int MaxDayInMonth[13];
    
        // Private members
        size_t m_year;
        size_t m_month;
        size_t m_day;   
    };
    
    // Define MaxDayInMonth
    const int Date::MaxDayInMonth[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    
    /// Add specified number of days to date
    Date Date::operator + (size_t days) const {
        // Maximum days in the month
        int nMaxDays(MaxDayInMonth[m_month] + (m_month == 2 && LeapYear(m_year) ? 1 : 0));
    
        // Initialize the Year, Month, Days
        int nYear(m_year);
        int nMonth(m_month);
        int nDays(m_day + days);
    
        // Iterate till it becomes a valid day of a month
        while (nDays > nMaxDays) {
            // Subtract the max number of days of current month
            nDays -= nMaxDays;
    
            // Advance to next month
            ++nMonth;
    
            // Falls on to next year?
            if (nMonth > 12) {
                nMonth = 1; // January
                ++nYear;    // Next year
            }
    
            // Update the max days of the new month
            nMaxDays = MaxDayInMonth[nMonth] + (nMonth == 2 && LeapYear(nYear) ? 1 : 0);
        }
    
        // Construct date
        return Date(nYear, nMonth, nDays);
    }
    
    /// Get the date string in yyyy/mm/dd format
    string Date::DateStr() {
        return to_string(m_year) 
            + string("/")
            + string(m_month < 10 ? string("0") + to_string(m_month) : to_string(m_month))
            + string("/")
            + string(m_day < 10 ? string("0") + to_string(m_day) : to_string(m_day)); 
    }
    
    
    int main() {
        // Add n days to a date
        cout << Date(2017, 6, 25).DateStr() << " + 10 days = "
             << (Date(2017, 6, 25) /* Given Date */ + 10 /* Days to add */).DateStr() << endl;
    
        return 0;
    }
    
    Output
    2017/06/25 + 10 days = 2017/07/05
    
    0 讨论(0)
  • 2020-12-06 08:01

    Here's what the solution looks like using algorithms published here by Howard Hinnant.

    int main() {
        int day_count = days_from_civil(1980, 5, 2);
        auto [year, month, day] = civil_from_days(day_count + 40);
        printf("%04i-%02i-%02-i\n", (int)year, (int)month, (int)day);
    }
    

    New date functionality has been approved for inclusion in C++20, though with a different API. A C++20 solution will probably look something like:

    #include <chrono>
    
    int main() {
        using namespace std::chrono;
        sys_days in_days = year_month_day{1980y, may, 2d};
        std::cout << year_month_day(in_days + days(40)) << '\n';
    }
    
    0 讨论(0)
  • 2020-12-06 08:14

    the easiest trick is to use time_t type and corresponding functions.

    mktime will convert tm structure to time_t. which is an integer value counting the seconds starting 01-Jan-1970.

    After you have a time_t value just add the seconds count you need (86400 per day).

    To convert back, use gmtime or localtime

    0 讨论(0)
  • 2020-12-06 08:15

    This code will print the date coming after 10 days. Change the value to N for a user-defined number.

    #include< iostream.h>
    
    #include< conio.h>
    
    struct date{int d,m,y;};
    
    void main()
    
        {
    
        date d1;
    
        void later (date);
    
        cout<<"ENTER A VALID DATE (dd/mm/yy)";
    
        cin>>d1.d>>d1.m>>d1.y;
    
        later(d1);
    
        getch();
    
        }
    
        void later(date d1)
    
        {
    
        int mdays[12]={31,28,31,30,31,30,31,31,30,31,30,31};
    
        if(((d1.y%4==0) && (d1.y%100!=0))||(d1.y%400==0))
        mdays[1]=29;
        d1.d=d1.d+10;
    
        if(d1.d>mdays[d1.m-1])
    
        {
    
        d1.d=d1.d-mdays[d1.m-1];
    
        d1.m++;
    
        if(d1.m>12)
    
        {d1.m=1;
    
        d1.y++;
    
        }
    
        }
        cout<<"DATE AFTER TEN DAYS IS "<<d1.d<<"\t"<<d1.m<<"\t"<<d1.y;
    
        getch();
    
        }
    
    0 讨论(0)
  • 2020-12-06 08:19

    Can you please tell me any good logic which works faster and have less complexity.

    If this exact thing is indeed a performance critical part of your application, you're likely doing something wrong. For the sake of clarity and correctness, you should stick to the existing solutions. Select the one that is most appropriate to your development environment.


    The C approach:

    #include <stdio.h>
    #include <time.h>
    
    int main()
    {        
        /* initialize */
        int y=1980, m=2, d=5;    
        struct tm t = { .tm_year=y-1900, .tm_mon=m-1, .tm_mday=d };
        /* modify */
        t.tm_mday += 40;
        mktime(&t);
        /* show result */
        printf("%s", asctime(&t)); /* prints: Sun Mar 16 00:00:00 1980 */
        return 0;
    }
    

    The C++ without using Boost approach:

    #include <ctime>
    #include <iostream>
    
    int main()
    {        
        // initialize
        int y=1980, m=2, d=5;
        std::tm t = {};
        t.tm_year = y-1900;
        t.tm_mon  = m-1;
        t.tm_mday = d;
        // modify
        t.tm_mday += 40;
        std::mktime(&t);
        // show result
        std::cout << std::asctime(&t); // prints: Sun Mar 16 00:00:00 1980
    }
    

    The Boost.Date_Time approach:

    #include <boost/date_time/posix_time/posix_time.hpp>
    #include <iostream>
    
    int main()
    {
        using namespace boost::gregorian;
        // initialize
        date d(1980,2,5);
        // modify
        d += days(40);
        // show result
        std::cout << d << '\n'; // prints: 1980-Mar-16
    }
    
    0 讨论(0)
  • 2020-12-06 08:19

    Just add to a time_t object for how many days you want.

    #define SECOND              1
    #define MINUTE              60 * SECOND
    #define HOUR                60 * MINUTE
    #define DAY                 24 * HOUR
    
    
    
    
    
    time_t curTime;
    time_t futureTime;
    
    time( & curTime );
    
    futureTime = curTime + (5 * DAY);
    
    struct tm * futureDate = gmtime(&futureTime);
    std::cout<<"5 days from now will be: "<<futureDate->tm_mday<<"/"<<futureDate->tm_mon+1<<"/"<<futureDate->tm_year+1900<<std::endl;
    
    0 讨论(0)
提交回复
热议问题