| 57 | } |
| 58 | |
| 59 | void nolocks_localtime(struct tm *tmp, time_t t, time_t tz, int dst) { |
| 60 | const time_t secs_min = 60; |
| 61 | const time_t secs_hour = 3600; |
| 62 | const time_t secs_day = 3600*24; |
| 63 | |
| 64 | t -= tz; /* Adjust for timezone. */ |
| 65 | t += 3600*dst; /* Adjust for daylight time. */ |
| 66 | time_t days = t / secs_day; /* Days passed since epoch. */ |
| 67 | time_t seconds = t % secs_day; /* Remaining seconds. */ |
| 68 | |
| 69 | tmp->tm_isdst = dst; |
| 70 | tmp->tm_hour = seconds / secs_hour; |
| 71 | tmp->tm_min = (seconds % secs_hour) / secs_min; |
| 72 | tmp->tm_sec = (seconds % secs_hour) % secs_min; |
| 73 | |
| 74 | /* 1/1/1970 was a Thursday, that is, day 4 from the POV of the tm structure |
| 75 | * where sunday = 0, so to calculate the day of the week we have to add 4 |
| 76 | * and take the modulo by 7. */ |
| 77 | tmp->tm_wday = (days+4)%7; |
| 78 | |
| 79 | /* Calculate the current year. */ |
| 80 | tmp->tm_year = 1970; |
| 81 | while(1) { |
| 82 | /* Leap years have one day more. */ |
| 83 | time_t days_this_year = 365 + is_leap_year(tmp->tm_year); |
| 84 | if (days_this_year > days) break; |
| 85 | days -= days_this_year; |
| 86 | tmp->tm_year++; |
| 87 | } |
| 88 | tmp->tm_yday = days; /* Number of day of the current year. */ |
| 89 | |
| 90 | /* We need to calculate in which month and day of the month we are. To do |
| 91 | * so we need to skip days according to how many days there are in each |
| 92 | * month, and adjust for the leap year that has one more day in February. */ |
| 93 | int mdays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; |
| 94 | mdays[1] += is_leap_year(tmp->tm_year); |
| 95 | |
| 96 | tmp->tm_mon = 0; |
| 97 | while(days >= mdays[tmp->tm_mon]) { |
| 98 | days -= mdays[tmp->tm_mon]; |
| 99 | tmp->tm_mon++; |
| 100 | } |
| 101 | |
| 102 | tmp->tm_mday = days+1; /* Add 1 since our 'days' is zero-based. */ |
| 103 | tmp->tm_year -= 1900; /* Surprisingly tm_year is year-1900. */ |
| 104 | } |
| 105 | |
| 106 | #ifdef LOCALTIME_TEST_MAIN |
| 107 | #include <stdio.h> |
no test coverage detected