kern
view src/klibc/time.c @ 37:2c401f69128e
finished with the klibc/time.c stuff
author | John Tsiombikas <nuclear@member.fsf.org> |
---|---|
date | Fri, 10 Jun 2011 19:54:47 +0300 |
parents | e70b1ab9613e |
children | e6f75f91e606 |
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 yrsec, yrdays, monsec, leap, day, num_days = 0;
73 int year = 1970;
74 time_t t = *tp;
76 while(t >= (yrsec = (yrdays = YEARDAYS(year)) * DAYSEC)) {
77 t -= yrsec;
78 year++;
79 num_days += yrdays;
80 }
81 tm->tm_year = year - 1900;
83 leap = is_leap_year(year);
84 tm->tm_mon = 0;
85 while(t >= (monsec = mdays[leap][tm->tm_mon] * DAYSEC)) {
86 num_days += mdays[leap][tm->tm_mon++];
87 t -= monsec;
88 }
90 day = t / DAYSEC;
91 tm->tm_mday = day + 1;
92 t %= DAYSEC;
94 tm->tm_hour = t / HOURSEC;
95 t %= HOURSEC;
97 tm->tm_min = t / MINSEC;
98 tm->tm_sec = t % MINSEC;
100 num_days += day;
101 tm->tm_wday = (num_days + 4) % 7;
102 tm->tm_yday = day_of_year(year, tm->tm_mon, day);
103 return tm;
104 }
106 int day_of_year(int year, int mon, int day)
107 {
108 int i, yday, leap;
110 leap = is_leap_year(year) ? 1 : 0;
111 yday = day;
113 for(i=0; i<mon; i++) {
114 yday += mdays[leap][i];
115 }
116 return yday;
117 }
119 static int is_leap_year(int yr)
120 {
121 /* exceptions first */
122 if(yr % 400 == 0) {
123 return 1;
124 }
125 if(yr % 100 == 0) {
126 return 0;
127 }
128 /* standard case */
129 return yr % 4 == 0;
130 }