Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // --------------------------------------------------------------------------------
- // Reply to https://r3dux.org/2017/08/how-to-convert-day-number-to-month-and-day/
- // No error checking, this is just an example implementation of the date algorithms
- // from: https://alcor.concordia.ca/~gpkatch/gdate-method.html.
- // --------------------------------------------------------------------------------
- #include <iostream>
- #include <vector>
- typedef std::vector<std::string> stringvec;
- typedef unsigned long ul;
- typedef signed long sl;
- // --------------------------------------------------------------------------------
- // Given the year, month and day, return the day number.
- // --------------------------------------------------------------------------------
- ul CalcDayNumFromDate(ul y, ul m, ul d)
- {
- m = (m + 9) % 12;
- y -= m / 10;
- ul dn = 365*y + y/4 - y/100 + y/400 + (m*306 + 5)/10 + (d - 1);
- return dn;
- }
- // --------------------------------------------------------------------------------
- // Given a day, calculate and return the date (in a string vector).
- // --------------------------------------------------------------------------------
- template<typename OUT>
- void CalcDateFromDayNum(ul day, OUT &retval)
- {
- ul y = (10000*day + 14780) / 3652425;
- sl ddd = day - (365*y + y/4 - y/100 + y/400);
- if (ddd < 0) {
- y--;
- ddd = day - (365*y + y/4 + y/100 + y/400);
- }
- ul mi = (100*ddd + 52) / 3060;
- ul mm = (mi + 2) % 12 + 1;
- y += (mi + 2) / 12;
- ul dd = ddd - (mi*306 + 5) / 10 + 1;
- retval.push_back(std::to_string(y));
- retval.push_back(std::to_string(mm));
- retval.push_back(std::to_string(dd));
- }
- // --------------------------------------------------------------------------------
- // Given the year and a day number, calculate and return the month and day.
- // --------------------------------------------------------------------------------
- stringvec CalcDayAndMonth(ul year, ul day)
- {
- stringvec date;
- ul start_day = CalcDayNumFromDate(year, 1, 1);
- CalcDateFromDayNum(start_day + day - 1, date);
- return date;
- }
- // --------------------------------------------------------------------------------
- // Program entry point.
- // --------------------------------------------------------------------------------
- int main(int argc, char **argv)
- {
- std::string year, day;
- std::string month[] =
- {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
- "Aug", "Sep", "Oct", "Nov", "Dec"};
- std::cout << "Enter the year (YYYY): ";
- getline(std::cin, year);
- std::cout << "Enter the day (between 0 and 365): ";
- getline(std::cin, day);
- stringvec date = CalcDayAndMonth(std::atoi(year.c_str()), std::atoi(day.c_str()));
- std::cout << "Month: " << month[std::atoi(date[1].c_str()) - 1]
- << ", Day: " << date[2] << std::endl;
- return 0;
- }
Add Comment
Please, Sign In to add comment