-
Notifications
You must be signed in to change notification settings - Fork 6
/
timeconvert.txt
87 lines (73 loc) · 2.51 KB
/
timeconvert.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//+ for datetime convert
#define SECOND_OF_DAY 86400
#define IS_LEAP_YEAR(y) ((y)%4 == 0 && (y)%100 != 0 || (y)%400 == 0)
#define BASE_YEAR 2018 // 1970 2018
static uint8_t DayOfMon[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
void DateTime2UnixTimeStamp(uint32_t *timestamp, RTC_Calendar_t *calendar)
{
uint16_t year, mon, day, hour, min, sec, i;
uint32_t nday = 0;
year = calendar->uwYear ;
mon = calendar->ubMonth;
day = calendar->ubDate ;
hour = calendar->ubHour ;
min = calendar->ubMin ;
sec = calendar->ubSec ;
for (i=BASE_YEAR; i<year; i++) {
nday += IS_LEAP_YEAR(i) ? 366 : 365;
}
for (i=1; i<mon; i++) {
nday += DayOfMon[i-1] + (i==2 && IS_LEAP_YEAR(year));
}
nday += (day - 1);
*timestamp = nday*SECOND_OF_DAY + (uint32_t)hour*3600 + (uint32_t)min*60 + sec;
}
void UnixTimeStamp2DateTime(RTC_Calendar_t *calendar, uint32_t timestamp)
{
uint32_t lsec = timestamp, lday;
lday = timestamp / SECOND_OF_DAY;
lsec = timestamp % SECOND_OF_DAY;
uint16_t i, j, iday;
i = BASE_YEAR;
while (lday >= IS_LEAP_YEAR(i) ? 366 : 365) {
lday -= IS_LEAP_YEAR(i) ? 366 : 365;
i++;
}
for (j=0; j<12; j++) {
iday = DayOfMon[j] + (j==1 && IS_LEAP_YEAR(i));
if (lday >= iday) lday -= iday;
else break;
}
calendar->uwYear = i;
calendar->ubMonth= j + 1;
calendar->ubDate = lday + 1;
calendar->ubHour = (lsec / 3600) % 24;
calendar->ubMin = (lsec % 3600) / 60;
calendar->ubSec = (lsec % 3600) % 60;
}
static int8_t is_dst_day(uint16_t year, uint32_t timestamp)
{
static uint16_t check_year = 0;
static uint32_t check_start = 0;
static uint32_t check_end = 0;
if (check_year != year) {
RTC_Calendar_t calendar = { year, 1, 1, 2, 0, 0};
int8_t dayofweek;
uint32_t ts;
calendar.ubMonth = 3;
calendar.ubDate = 1;
DateTime2UnixTimeStamp(&ts, &calendar);
dayofweek = (ts / (60 * 60 * 24)) % 7;
calendar.ubDate = 6 - dayofweek + 1 + 7;
DateTime2UnixTimeStamp(&check_start, &calendar);
calendar.ubMonth = 11;
calendar.ubDate = 1;
DateTime2UnixTimeStamp(&ts, &calendar);
dayofweek = (ts / (60 * 60 * 24)) % 7;
calendar.ubDate = 6 - dayofweek + 1 + 0;
DateTime2UnixTimeStamp(&check_end , &calendar);
check_year = year;
}
return timestamp >= check_start && timestamp < check_end;
}
//- for datetime convert