libc_time.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * Originally released by the musl project (http://www.musl-libc.org/) under the
  3. * MIT license. Taken from the file /src/time/__secs_to_tm.c
  4. */
  5. #include "libc_time.h"
  6. /* 2000-03-01 (mod 400 year, immediately after feb29 */
  7. #define LEAPOCH (946684800LL + 86400*(31+29))
  8. #define DAYS_PER_400Y (365*400 + 97)
  9. #define DAYS_PER_100Y (365*100 + 24)
  10. #define DAYS_PER_4Y (365*4 + 1)
  11. int __secs_to_tm(long long t, struct tm *tm)
  12. {
  13. long long days, secs, years;
  14. int remdays, remsecs, remyears;
  15. int qc_cycles, c_cycles, q_cycles;
  16. int months;
  17. int wday, yday, leap;
  18. static const char days_in_month[] = {31,30,31,30,31,31,30,31,30,31,31,29};
  19. /* Reject time_t values whose year would overflow int */
  20. if (t < INT_MIN * 31622400LL || t > INT_MAX * 31622400LL)
  21. return -1;
  22. secs = t - LEAPOCH;
  23. days = secs / 86400LL;
  24. remsecs = (int)(secs % 86400);
  25. if (remsecs < 0) {
  26. remsecs += 86400;
  27. --days;
  28. }
  29. wday = (int)((3+days)%7);
  30. if (wday < 0) wday += 7;
  31. qc_cycles = (int)(days / DAYS_PER_400Y);
  32. remdays = (int)(days % DAYS_PER_400Y);
  33. if (remdays < 0) {
  34. remdays += DAYS_PER_400Y;
  35. --qc_cycles;
  36. }
  37. c_cycles = remdays / DAYS_PER_100Y;
  38. if (c_cycles == 4) --c_cycles;
  39. remdays -= c_cycles * DAYS_PER_100Y;
  40. q_cycles = remdays / DAYS_PER_4Y;
  41. if (q_cycles == 25) --q_cycles;
  42. remdays -= q_cycles * DAYS_PER_4Y;
  43. remyears = remdays / 365;
  44. if (remyears == 4) --remyears;
  45. remdays -= remyears * 365;
  46. leap = !remyears && (q_cycles || !c_cycles);
  47. yday = remdays + 31 + 28 + leap;
  48. if (yday >= 365+leap) yday -= 365+leap;
  49. years = remyears + 4*q_cycles + 100*c_cycles + 400LL*qc_cycles;
  50. for (months=0; days_in_month[months] <= remdays; ++months)
  51. remdays -= days_in_month[months];
  52. if (years+100 > INT_MAX || years+100 < INT_MIN)
  53. return -1;
  54. tm->tm_year = (int)(years + 100);
  55. tm->tm_mon = months + 2;
  56. if (tm->tm_mon >= 12) {
  57. tm->tm_mon -=12;
  58. ++tm->tm_year;
  59. }
  60. tm->tm_mday = remdays + 1;
  61. tm->tm_wday = wday;
  62. tm->tm_yday = yday;
  63. tm->tm_hour = remsecs / 3600;
  64. tm->tm_min = remsecs / 60 % 60;
  65. tm->tm_sec = remsecs % 60;
  66. return 0;
  67. }