Search code examples
c++

Calculating day of year from date


I need to calculate the day number of a given date. The year has 366 days in it. Each month however has a different value and I have to assign the values. Is there a quicker way to do it rather than the way I am going about it?

#include<iostream>
using namespace std;
int main()
{
   int day, month, year, dayNumber;

   cout<< "Please enter the month, by numerical value:";
   cin>> month;
   cout<<"Please enter the day, by numerical value:";
   cin>> day;
   cout<<"Please enter the year, by numerical value:";
   cin>> year;
   if (month == 1)
   {
      dayNumber= day;
      cout<< "Month;" << '\t'<< month << '\n'
          << "Day:"<<'\t'<< day<< '\n'
          << "Year:"<<'\t'<< year<<'\n'
          << "Day Number:"<< '\t'<< dayNumber<< endl;
   }
   else if(month==2)
   {
      dayNumber= day+31; 
   }
}

Solution

  • In many ways it is probably best to avoid hand-rolling this.

    Use boost:

    #include <boost/date_time/gregorian/gregorian.hpp>
    
    //...
    try {
        boost::gregorian::date d(year, month, day);
        dayNumber = d.day_of_year();
    }
    catch (std::out_of_range& e) {
        // Alternatively catch bad_year etc exceptions.
        std::cout << "Bad date: " << e.what() << std::endl;
    }
    

    As James Kanze suggests you could also use mktime to avoid dependency on boost (untested):

      tm timeinfo = {};
      timeinfo.tm_year = year - 1900;
      timeinfo.tm_mon = month - 1;
      timeinfo.tm_mday = day;
      mktime(&timeinfo);
      dayNumber = timeinfo.tm_yday;