New developer version 0.6.8; added select () function; added demonstrating example...
[ZeXOS.git] / libc / time / mktime.c
blob6b826d998ddc7d6dff2e633595ba66b81e504762
1 /*
2 * ZeX/OS
3 * Copyright (C) 2009 Tomas 'ZeXx86' Jedrzejek (zexx86@zexos.org)
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #include <time.h>
22 #define MINUTE 60
23 #define HOUR (60 * MINUTE)
24 #define DAY (24 * HOUR)
25 #define YEAR (365 * DAY)
27 static int is_leap_year (int year)
29 if (year % 4 == 0) {
30 if (year % 100 == 0) {
31 if (year % 400 == 0)
32 return 1;
33 else
34 return 0;
37 return 1;
39 return 0;
42 static int count_leap_years (int epoch, int year)
44 int i, result = 0;
45 for (i = epoch; i < year; i ++)
46 if (is_leap_year(i))
47 result ++;
49 return result;
52 static int get_day (int year, int mon, int day)
54 int result;
56 switch (mon) {
57 case 0:
58 result = 0;
59 break;
60 case 1:
61 result = 31;
62 break; /* 1: 31 */
63 case 2:
64 result = 59;
65 break; /* 2: 31+28 */
66 case 3:
67 result = 90;
68 break; /* 3: 59+31 */
69 case 4:
70 result = 120;
71 break; /* 4: 90+30 */
72 case 5:
73 result = 151;
74 break; /* 5: 120+31 */
75 case 6:
76 result = 181;
77 break; /* 6: 151+30 */
78 case 7:
79 result = 212;
80 break; /* 7: 181+31 */
81 case 8:
82 result = 243;
83 break; /* 8: 212+31 */
84 case 9:
85 result = 273;
86 break; /* 9: 243+30 */
87 case 10:
88 result = 304;
89 break; /* 10: 273+31 */
90 case 11:
91 result = 334;
92 break; /* 11: 304+30 */
93 default:
94 break;
97 if (is_leap_year (year) && mon > 2)
98 result ++;
100 result += day - 1;
102 return result;
105 time_t mktime (struct tm *tm)
107 if (!tm)
108 return -1;
110 unsigned long result = 0;
112 result = tm->tm_sec;
113 result += tm->tm_min * MINUTE;
114 result += tm->tm_hour * HOUR;
115 result += get_day (tm->tm_year, tm->tm_mon - 1, tm->tm_mday) * DAY;
116 result += (tm->tm_year - EPOCH_YEAR) * YEAR;
117 result += count_leap_years (EPOCH_YEAR, tm->tm_year) * DAY;
119 return result;