Efficient algorithm for converting number of days to years (including leap years)

后端 未结 10 1977
逝去的感伤
逝去的感伤 2021-02-05 17:04

The problem

I am writing a class for holding dates in c++, and I found the following problem:

I have a number of days N since a reference date (in

10条回答
  •  感情败类
    2021-02-05 17:19

    Here are a few pointers. Note: For this exercise I will assume that when N=0 that Y % 400 == 0.

    1: There are a fixed number of days in each 400 year period (400 * 365) + 100 + 1 - 4.

    The +100 is for the leap years, the +1 is for the leap year every 400 years and the -4 is for not having a leap year every 100 years.

    So your first line of code will be:

    GetDate(int N, int &Y, int &M, int &D) {
      const int DAYS_IN_400_YEARS = (400*365)+97;
      int year = (N / DAYS_IN_400_YEARS) * 400;
      N = N % DAYS_IN_400_YEARS;
    

    2: You can make your life a great deal easier if you treat March 1st as the first day of the year

    3: Adding to the code in (1), we can work out the year. Bear in mind that every fourth century begins with a leap year. So you can complete the calculation of the year with the following:

      const int DAYS_IN_100_YEARS = (100*365) + 24;
      year += 100 * (N / DAYS_IN_100_YEARS) + (N < DAYS_IN_100_YEARS ? 1 : 0); // Add an extra day for the first leap year that occurs every 400 years.
      N = N - (N < DAYS_IN_100_YEARS ? 1 : 0);
      N = N % DAYS_IN_400_YEARS;
    

    4: Now you've sorted out the years, the rest is easy as pie (just remember (2), and the process is easy).

    Alternatively you could use boost::date.

提交回复
热议问题