kern

view src/klibc/time.c @ 38:e6f75f91e606

- added makefile pattern to produce assembly output from c source files. - removed a commented out previous version of the gmtime_r function in klibc/time.c
author John Tsiombikas <nuclear@member.fsf.org>
date Fri, 10 Jun 2011 23:19:25 +0300
parents 2c401f69128e
children 92297f65aaef
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;
87 leap = is_leap_year(year);
88 tm->tm_mon = 0;
89 while(days >= mdays[leap][tm->tm_mon]) {
90 days -= mdays[leap][tm->tm_mon++];
91 }
93 tm->tm_mday = days + 1;
95 tm->tm_hour = t / HOURSEC;
96 t %= HOURSEC;
97 tm->tm_min = t / MINSEC;
98 tm->tm_sec = t % MINSEC;
100 tm->tm_yday = day_of_year(year, tm->tm_mon, days);
101 return tm;
102 }
104 int day_of_year(int year, int mon, int day)
105 {
106 int i, yday, leap;
108 leap = is_leap_year(year) ? 1 : 0;
109 yday = day;
111 for(i=0; i<mon; i++) {
112 yday += mdays[leap][i];
113 }
114 return yday;
115 }
117 static int is_leap_year(int yr)
118 {
119 /* exceptions first */
120 if(yr % 400 == 0) {
121 return 1;
122 }
123 if(yr % 100 == 0) {
124 return 0;
125 }
126 /* standard case */
127 return yr % 4 == 0;
128 }