libc_time.c 2.4 KB

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