gmtime_r.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * Copyright (c) 2006-2018, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2018-10-26 zylx first version
  9. */
  10. #if defined(__CC_ARM) || defined(__CLANG_ARM) || defined (__IAR_SYSTEMS_ICC__)
  11. #include <sys/time.h>
  12. /* seconds per day */
  13. #define SPD 24*60*60
  14. /* days per month -- nonleap! */
  15. const short __spm[13] =
  16. {
  17. 0,
  18. (31),
  19. (31 + 28),
  20. (31 + 28 + 31),
  21. (31 + 28 + 31 + 30),
  22. (31 + 28 + 31 + 30 + 31),
  23. (31 + 28 + 31 + 30 + 31 + 30),
  24. (31 + 28 + 31 + 30 + 31 + 30 + 31),
  25. (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31),
  26. (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30),
  27. (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31),
  28. (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30),
  29. (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31),
  30. };
  31. int __isleap(int year)
  32. {
  33. /* every fourth year is a leap year except for century years that are
  34. * not divisible by 400. */
  35. /* return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); */
  36. return (!(year % 4) && ((year % 100) || !(year % 400)));
  37. }
  38. /**
  39. * This function will convert Time (Restartable)
  40. *
  41. * @param timep the timestamp
  42. * @param the structure to stores information
  43. *
  44. * @return the structure to stores information
  45. *
  46. */
  47. struct tm *gmtime_r(const time_t *timep, struct tm *r)
  48. {
  49. time_t i;
  50. register time_t work = *timep % (SPD);
  51. r->tm_sec = work % 60;
  52. work /= 60;
  53. r->tm_min = work % 60;
  54. r->tm_hour = work / 60;
  55. work = *timep / (SPD);
  56. r->tm_wday = (4 + work) % 7;
  57. for (i = 1970;; ++i)
  58. {
  59. register time_t k = __isleap(i) ? 366 : 365;
  60. if (work >= k)
  61. work -= k;
  62. else
  63. break;
  64. }
  65. r->tm_year = i - 1900;
  66. r->tm_yday = work;
  67. r->tm_mday = 1;
  68. if (__isleap(i) && (work > 58))
  69. {
  70. if (work == 59)
  71. r->tm_mday = 2; /* 29.2. */
  72. work -= 1;
  73. }
  74. for (i = 11; i && (__spm[i] > work); --i)
  75. ;
  76. r->tm_mon = i;
  77. r->tm_mday += work - __spm[i];
  78. return r;
  79. }
  80. #endif /* end of __CC_ARM or __CLANG_ARM or __IAR_SYSTEMS_ICC__ */