xref: /nrf52832-nimble/rt-thread/components/libc/compilers/common/gmtime_r.c (revision 104654410c56c573564690304ae786df310c91fc)
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 
11 #if defined(__CC_ARM) || defined(__CLANG_ARM) || defined (__IAR_SYSTEMS_ICC__)
12 #include <sys/time.h>
13 
14 /* seconds per day */
15 #define SPD 24*60*60
16 
17 /* days per month -- nonleap! */
18 const short __spm[13] =
19 {
20     0,
21     (31),
22     (31 + 28),
23     (31 + 28 + 31),
24     (31 + 28 + 31 + 30),
25     (31 + 28 + 31 + 30 + 31),
26     (31 + 28 + 31 + 30 + 31 + 30),
27     (31 + 28 + 31 + 30 + 31 + 30 + 31),
28     (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31),
29     (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30),
30     (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31),
31     (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30),
32     (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31),
33 };
34 
__isleap(int year)35 int __isleap(int year)
36 {
37     /* every fourth year is a leap year except for century years that are
38      * not divisible by 400. */
39     /*  return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); */
40     return (!(year % 4) && ((year % 100) || !(year % 400)));
41 }
42 
43 /**
44  * This function will convert Time (Restartable)
45  *
46  * @param timep the timestamp
47  * @param the structure to stores information
48  *
49  * @return the structure to stores information
50  *
51  */
gmtime_r(const time_t * timep,struct tm * r)52 struct tm *gmtime_r(const time_t *timep, struct tm *r)
53 {
54     time_t i;
55     register time_t work = *timep % (SPD);
56     r->tm_sec = work % 60;
57     work /= 60;
58     r->tm_min = work % 60;
59     r->tm_hour = work / 60;
60     work = *timep / (SPD);
61     r->tm_wday = (4 + work) % 7;
62     for (i = 1970;; ++i)
63     {
64         register time_t k = __isleap(i) ? 366 : 365;
65         if (work >= k)
66             work -= k;
67         else
68             break;
69     }
70     r->tm_year = i - 1900;
71     r->tm_yday = work;
72 
73     r->tm_mday = 1;
74     if (__isleap(i) && (work > 58))
75     {
76         if (work == 59)
77             r->tm_mday = 2; /* 29.2. */
78         work -= 1;
79     }
80 
81     for (i = 11; i && (__spm[i] > work); --i)
82         ;
83     r->tm_mon = i;
84     r->tm_mday += work - __spm[i];
85     return r;
86 }
87 #endif /* end of __CC_ARM or __CLANG_ARM or __IAR_SYSTEMS_ICC__ */
88 
89