Dates.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. string dayOfWeek[] = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
  6. // converts Gregorian date to integer (Julian day number)
  7. int dateToInt (int m, int d, int y){
  8. return
  9. 1461 * (y + 4800 + (m - 14) / 12) / 4 +
  10. 367 * (m - 2 - (m - 14) / 12 * 12) / 12 -
  11. 3 * ((y + 4900 + (m - 14) / 12) / 100) / 4 +
  12. d - 32075;
  13. }
  14. // converts integer (Julian day number) to Gregorian date: month/day/year
  15. void intToDate (int jd, int &m, int &d, int &y){
  16. int x, n, i, j;
  17. x = jd + 68569;
  18. n = 4 * x / 146097;
  19. x -= (146097 * n + 3) / 4;
  20. i = (4000 * (x + 1)) / 1461001;
  21. x -= 1461 * i / 4 - 31;
  22. j = 80 * x / 2447;
  23. d = x - 2447 * j / 80;
  24. x = j / 11;
  25. m = j + 2 - 12 * x;
  26. y = 100 * (n - 49) + i + x;
  27. }
  28. // converts integer (Julian day number) to day of week
  29. string intToDay (int jd){
  30. return dayOfWeek[jd % 7];
  31. }
  32. void test() {
  33. int jd = dateToInt (3, 24, 2004);
  34. int m, d, y;
  35. intToDate (jd, m, d, y);
  36. string day = intToDay (jd);
  37. // expected output:
  38. // 2453089
  39. // 3/24/2004
  40. // Wed
  41. cout << jd << endl
  42. << m << "/" << d << "/" << y << endl
  43. << day << endl;
  44. }