#include long week( int day, int month, int year ){ // Returns the number of the ISO week in the year (from 1 to 53) // containing the given date (assumed valid, and in the Gregorian // calendar); more exactly, the returned value is yyyyww, where yyyy // is the year and ww the ISO week number. int m, start, yearDay, lastDay, lastSunday; const int nMonths = 12; static int monthDays[nMonths + 1] = { 0, 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // - Initializes correctly the number of days in February; // - stores in lastDay the total number of days in the given year; // - stores in yearDay the total number of days in the year not // after the given date ("day-of-the-year"). if (isLeap(year)) { monthDays[2] = 29; lastDay = 366; } else { monthDays[2] = 28; lastDay = 365; } for (m = 0, yearDay = day; ++m < month; ) { yearDay += monthDays[m]; } // - Computes in "start" the first day of the first week of this // year ("start" may be negative if the beginning of the first // week is in the previous year); // - computes in "lastSunday" the date of the last Sunday in // December. // // weekDay(day, month, year) is a procedure that computes the day of // the week corresponding to a given date, returning 0 for Monday, 1 // for Tuesday, ..., 6 for Sunday. start = 4 - weekDay(4, 1, year); lastSunday = weekDay(31, 12, year); lastSunday = lastSunday == 6 ? 31 : 30-lastSunday; std::cout << "- The first ISO week of the year " << year << " begins on Monday "; if (start < 1) { std::cout << 31+start << "-Dec-" << year-1 << std::endl; } else { std::cout << start << "-Jan-" << year << std::endl; } // After the following printout, "lastSunday" is changed to the // day-of-the-year number of the Sunday ending the last ISO week of // the current year. std::cout << "- The last ISO week of the year " << year << " ends on Sunday "; if (31-lastSunday < 4) { std::cout << lastSunday << "-Dec-" << year << std::endl; lastSunday = lastDay - (31 - lastSunday); } else { std::cout << lastSunday+7-31 << "-Jan-" << year+1 << std::endl; lastSunday = lastDay + lastSunday+7-31; } // - If the day-of-the-year is before "start", we are in the last // week of the previous year (the week of December 31); // - if not, and if the given date is after "lastSunday", we are in // the first week of the next year; // - in all the other cases, we compute the number of the week // normally. if (yearDay < start) return week(31, 12, year-1); if (yearDay > lastSunday) return (year + 1)*100 + 1; return year*100 + ((yearDay - start) / 7 + 1); }