libc_time.c 2.2 KB

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