1
2
3
4
5
6
7#include <common.h>
8#include <command.h>
9#include <errno.h>
10#include <rtc.h>
11#include <linux/time.h>
12
13#if defined(CONFIG_LIB_DATE) || defined(CONFIG_TIMESTAMP)
14
15#define FEBRUARY 2
16#define STARTOFTIME 1970
17#define SECDAY 86400L
18#define SECYR (SECDAY * 365)
19#define leapyear(year) ((year) % 4 == 0)
20#define days_in_year(a) (leapyear(a) ? 366 : 365)
21#define days_in_month(a) (month_days[(a) - 1])
22
23static int month_offset[] = {
24 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
25};
26
27
28
29
30int rtc_calc_weekday(struct rtc_time *tm)
31{
32 int leaps_to_date;
33 int last_year;
34 int day;
35
36 if (tm->tm_year < 1753)
37 return -1;
38 last_year = tm->tm_year - 1;
39
40
41 leaps_to_date = last_year / 4 - last_year / 100 + last_year / 400;
42
43
44
45
46
47
48
49 if (tm->tm_year % 4 == 0 &&
50 ((tm->tm_year % 100 != 0) || (tm->tm_year % 400 == 0)) &&
51 tm->tm_mon > 2) {
52
53 day = 1;
54 } else {
55 day = 0;
56 }
57
58 day += last_year * 365 + leaps_to_date + month_offset[tm->tm_mon - 1] +
59 tm->tm_mday;
60 tm->tm_wday = day % 7;
61
62 return 0;
63}
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81unsigned long rtc_mktime(const struct rtc_time *tm)
82{
83 int mon = tm->tm_mon;
84 int year = tm->tm_year;
85 int days, hours;
86
87 mon -= 2;
88 if (0 >= (int)mon) {
89 mon += 12;
90 year -= 1;
91 }
92
93 days = (unsigned long)(year / 4 - year / 100 + year / 400 +
94 367 * mon / 12 + tm->tm_mday) +
95 year * 365 - 719499;
96 hours = days * 24 + tm->tm_hour;
97 return (hours * 60 + tm->tm_min) * 60 + tm->tm_sec;
98}
99
100#endif
101
102#ifdef CONFIG_LIB_DATE
103
104time64_t mktime64(const unsigned int year, const unsigned int mon,
105 const unsigned int day, const unsigned int hour,
106 const unsigned int min, const unsigned int sec)
107{
108 struct rtc_time time;
109
110 time.tm_year = year;
111 time.tm_mon = mon;
112 time.tm_mday = day;
113 time.tm_hour = hour;
114 time.tm_min = min;
115 time.tm_sec = sec;
116
117 return (time64_t)rtc_mktime((const struct rtc_time *)&time);
118}
119#endif
120