kern

view src/klibc/time.c @ 39:92297f65aaef

- removed redundant call to day_of_year in gmtime_r
author John Tsiombikas <nuclear@member.fsf.org>
date Sun, 12 Jun 2011 01:46:53 +0300
parents e6f75f91e606
children 710739e33da8
line source
1 #include <stdio.h>
2 #include "time.h"
3 #include "rtc.h"
4 #include "timer.h"
5 #include "config.h"
7 #define MINSEC 60
8 #define HOURSEC (60 * MINSEC)
9 #define DAYSEC (24 * HOURSEC)
10 #define YEARDAYS(x) (is_leap_year(x) ? 366 : 365)
12 static int is_leap_year(int yr);
14 static int mdays[2][12] = {
15 {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
16 {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
17 };
19 static char *wday[] = {
20 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
21 };
22 static char *mon[] = {
23 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
24 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
25 };
28 time_t time(time_t *tp)
29 {
30 time_t res = start_time + nticks / TICK_FREQ_HZ;
32 if(tp) *tp = res;
33 return res;
34 }
36 char *asctime(struct tm *tm)
37 {
38 static char buf[64];
39 return asctime_r(tm, buf);
40 }
42 char *asctime_r(struct tm *tm, char *buf)
43 {
44 sprintf(buf, "%s %s %d %02d:%02d:%02d %d\n", wday[tm->tm_wday],
45 mon[tm->tm_mon], tm->tm_mday, tm->tm_hour, tm->tm_min,
46 tm->tm_sec, tm->tm_year + 1900);
47 return buf;
48 }
50 time_t mktime(struct tm *tm)
51 {
52 int i, num_years = tm->tm_year - 70;
53 int year = 1970;
54 int days = day_of_year(tm->tm_year + 1900, tm->tm_mon, tm->tm_mday - 1);
56 for(i=0; i<num_years; i++) {
57 days += YEARDAYS(year++);
58 }
60 return (time_t)days * DAYSEC + tm->tm_hour * HOURSEC +
61 tm->tm_min * MINSEC + tm->tm_sec;
62 }
64 struct tm *gmtime(time_t *tp)
65 {
66 static struct tm tm;
67 return gmtime_r(tp, &tm);
68 }
70 struct tm *gmtime_r(time_t *tp, struct tm *tm)
71 {
72 int year, days, leap, yrdays;
73 time_t t;
75 year = 1970;
76 days = *tp / DAYSEC;
77 t = *tp % DAYSEC;
79 tm->tm_wday = (days + 4) % 7;
81 while(days >= (yrdays = YEARDAYS(year))) {
82 days -= yrdays;
83 year++;
84 }
85 tm->tm_year = year - 1900;
86 tm->tm_yday = days;
88 leap = is_leap_year(year);
89 tm->tm_mon = 0;
90 while(days >= mdays[leap][tm->tm_mon]) {
91 days -= mdays[leap][tm->tm_mon++];
92 }
94 tm->tm_mday = days + 1;
96 tm->tm_hour = t / HOURSEC;
97 t %= HOURSEC;
98 tm->tm_min = t / MINSEC;
99 tm->tm_sec = t % MINSEC;
100 return tm;
101 }
103 int day_of_year(int year, int mon, int day)
104 {
105 int i, yday, leap;
107 leap = is_leap_year(year) ? 1 : 0;
108 yday = day;
110 for(i=0; i<mon; i++) {
111 yday += mdays[leap][i];
112 }
113 return yday;
114 }
116 static int is_leap_year(int yr)
117 {
118 /* exceptions first */
119 if(yr % 400 == 0) {
120 return 1;
121 }
122 if(yr % 100 == 0) {
123 return 0;
124 }
125 /* standard case */
126 return yr % 4 == 0;
127 }