Dates.cc 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Routines for performing computations on dates. In these routines,
  2. // months are expressed as integers from 1 to 12, days are expressed
  3. // as integers from 1 to 31, and years are expressed as 4-digit
  4. // integers.
  5. #include <iostream>
  6. #include <string>
  7. using namespace std;
  8. string dayOfWeek[] = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
  9. // converts Gregorian date to integer (Julian day number)
  10. int dateToInt (int m, int d, int y){
  11. return
  12. 1461 * (y + 4800 + (m - 14) / 12) / 4 +
  13. 367 * (m - 2 - (m - 14) / 12 * 12) / 12 -
  14. 3 * ((y + 4900 + (m - 14) / 12) / 100) / 4 +
  15. d - 32075;
  16. }
  17. // converts integer (Julian day number) to Gregorian date: month/day/year
  18. void intToDate (int jd, int &m, int &d, int &y){
  19. int x, n, i, j;
  20. x = jd + 68569;
  21. n = 4 * x / 146097;
  22. x -= (146097 * n + 3) / 4;
  23. i = (4000 * (x + 1)) / 1461001;
  24. x -= 1461 * i / 4 - 31;
  25. j = 80 * x / 2447;
  26. d = x - 2447 * j / 80;
  27. x = j / 11;
  28. m = j + 2 - 12 * x;
  29. y = 100 * (n - 49) + i + x;
  30. }
  31. // converts integer (Julian day number) to day of week
  32. string intToDay (int jd){
  33. return dayOfWeek[jd % 7];
  34. }
  35. int main (int argc, char **argv){
  36. int jd = dateToInt (3, 24, 2004);
  37. int m, d, y;
  38. intToDate (jd, m, d, y);
  39. string day = intToDay (jd);
  40. // expected output:
  41. // 2453089
  42. // 3/24/2004
  43. // Wed
  44. cout << jd << endl
  45. << m << "/" << d << "/" << y << endl
  46. << day << endl;
  47. }