time.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <time.h>
  4. /* We use this instead of memcmp because some broken C libraries
  5. * add additional nonstandard fields to struct tm... */
  6. int tm_cmp(struct tm tm1, struct tm tm2)
  7. {
  8. return tm1.tm_sec != tm2.tm_sec ||
  9. tm1.tm_min != tm2.tm_min ||
  10. tm1.tm_hour != tm2.tm_hour ||
  11. tm1.tm_mday != tm2.tm_mday ||
  12. tm1.tm_mon != tm2.tm_mon ||
  13. tm1.tm_year != tm2.tm_year ||
  14. tm1.tm_wday != tm2.tm_wday ||
  15. tm1.tm_yday != tm2.tm_yday ||
  16. tm1.tm_isdst!= tm2.tm_isdst;
  17. }
  18. char *tm_str(struct tm tm)
  19. {
  20. static int i;
  21. static char b[4][64];
  22. i = (i+1)%4;
  23. snprintf(b[i], sizeof b[i],
  24. "s=%.2d m=%.2d h=%.2d mday=%.2d mon=%.2d year=%.4d wday=%d yday=%d isdst=%d",
  25. tm.tm_sec, tm.tm_min, tm.tm_hour,
  26. tm.tm_mday, tm.tm_mon, tm.tm_year,
  27. tm.tm_wday, tm.tm_yday, tm.tm_isdst);
  28. return b[i];
  29. }
  30. #define TM(ss,mm,hh,md,mo,yr,wd,yd,dst) (struct tm){ \
  31. .tm_sec = ss, .tm_min = mm, .tm_hour = hh, \
  32. .tm_mday = md, .tm_mon = mo, .tm_year = yr, \
  33. .tm_wday = wd, .tm_yday = yd, .tm_isdst = dst }
  34. #define TM_EPOCH TM(0,0,0,1,0,70,4,0,0)
  35. #define TM_Y2038_1S TM(7,14,3,19,0,138,2,18,0)
  36. #define TM_Y2038 TM(8,14,3,19,0,138,2,18,0)
  37. #define TEST_TM(r,x,m) (!tm_cmp((r),(x)) || \
  38. (printf(__FILE__ ":%d: %s failed:\n\tresult: %s\n\texpect: %s\n", __LINE__, \
  39. m, tm_str((r)), tm_str((x))), err++, 0) )
  40. #define TEST(r, f, x, m) ( \
  41. ((r) = (f)) == (x) || \
  42. (printf(__FILE__ ":%d: %s failed (" m ")\n", __LINE__, #f, r, x), err++, 0) )
  43. int main(void)
  44. {
  45. struct tm tm, *tm_p;
  46. time_t t;
  47. int err=0;
  48. putenv("TZ=GMT");
  49. tzset();
  50. t=0; tm_p = gmtime(&t);
  51. TEST_TM(*tm_p, TM_EPOCH, "gmtime(0)");
  52. tm = TM_Y2038_1S;
  53. t = mktime(&tm);
  54. tm = *(gmtime(&t));
  55. TEST_TM(*tm_p, TM_Y2038_1S, "mktime/gmtime(Y2038-1)");
  56. tm = TM_Y2038;
  57. t = mktime(&tm);
  58. tm = *(gmtime(&t));
  59. TEST_TM(*tm_p, TM_Y2038, "mktime/gmtime(Y2038)");
  60. /* FIXME: set a TZ var and check DST boundary conditions */
  61. return err;
  62. }