2
0

mktime.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include <assert.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <time.h>
  5. #include "test_helpers.h"
  6. int check(time_t input) {
  7. struct tm *t = localtime(&input);
  8. ERROR_IF(localtime, t, == NULL);
  9. time_t output = mktime(t);
  10. ERROR_IF(mktime, output, == (time_t)-1);
  11. printf("%ld = %ld\n", input, output);
  12. if (input != output) {
  13. printf(
  14. "Year %d, Day of year: %d, Month %d, Day of month: %d, Day of week: %d, %d:%d:%d\n",
  15. t->tm_year, t->tm_yday, t->tm_mon, t->tm_mday, t->tm_wday, t->tm_hour, t->tm_min, t->tm_sec
  16. );
  17. puts("Failed!");
  18. return 1;
  19. }
  20. return 0;
  21. }
  22. int main(void) {
  23. struct tm t = { 0 };
  24. t.tm_year = 71;
  25. t.tm_mday = 1;
  26. printf("%ld\n", mktime(&t));
  27. int day = 60 * 60 * 24;
  28. time_t inputs[] = { -(day * 33), -day, -500, 0, 1531454950 };
  29. for (int i = 0; i < 5; i += 1) {
  30. if (check(inputs[i])) {
  31. exit(EXIT_FAILURE);
  32. }
  33. }
  34. srand(time(NULL));
  35. for (int i = 0; i < 10; i += 1) {
  36. time_t input = (time_t) rand();
  37. struct tm *time = localtime(&input);
  38. ERROR_IF(localtime, time, == NULL);
  39. time_t output = mktime(time);
  40. ERROR_IF(mktime, output, == (time_t)-1);
  41. if (input != output) {
  42. // asctime has newline
  43. printf("Comparison %ld == %ld failed. Time: %s", input, output, asctime(time));
  44. }
  45. }
  46. }