-
Notifications
You must be signed in to change notification settings - Fork 47
/
Unixtime.SCL
90 lines (68 loc) · 2.33 KB
/
Unixtime.SCL
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
88
89
90
// Convert system time to unix time
// (seconds until 1970-01-01 00:00)
FUNCTION Unixtime : DWORD
VAR_INPUT
END_VAR
VAR_TEMP
leapyears : INT;
days_from_1970 : DINT;
days_from_BeginOfYear : ARRAY[1..12] OF INT;
l_unixtime : DINT;
sfc1_ret_val : INT;
CDT_systemtime : DATE_AND_TIME;
systemtime AT CDT_systemtime : STRUCT
year_CDT : BYTE; // 1970 ... 2038
month_CDT : BYTE;
day_CDT : BYTE;
hour_CDT : BYTE;
minute_CDT : BYTE;
second_CDT : BYTE;
END_STRUCT;
year : INT; // 1970 ... 2038
month : INT;
day : INT;
hour : INT;
minute : INT;
second : INT;
END_VAR
leapyears := 0;
days_from_1970 := 0;
// days of current month without leap day
days_from_BeginOfYear[1] := 0;
days_from_BeginOfYear[2] := 31;
days_from_BeginOfYear[3] := 59;
days_from_BeginOfYear[4] := 90;
days_from_BeginOfYear[5] := 120;
days_from_BeginOfYear[6] := 151;
days_from_BeginOfYear[7] := 181;
days_from_BeginOfYear[8] := 212;
days_from_BeginOfYear[9] := 243;
days_from_BeginOfYear[10] := 273;
days_from_BeginOfYear[11] := 304;
days_from_BeginOfYear[12] := 334;
// read system time
sfc1_ret_val := READ_CLK(CDT := CDT_systemtime);
year := BCD_TO_INT(systemtime.year_CDT) + 2000;
month := BCD_TO_INT(systemtime.month_CDT);
day := BCD_TO_INT(systemtime.day_CDT);
hour := BCD_TO_INT(systemtime.hour_CDT);
minute := BCD_TO_INT(systemtime.minute_CDT);
second := BCD_TO_INT(systemtime.second_CDT);
// sum of leap years since 1979 (without current leap year)
leapyears := ((year-1)-1968)/4
- ((year-1)-1900)/100
+ ((year-1)-1600)/400;
days_from_1970 := (year-1970)*365 + leapyears
+ days_from_BeginOfYear[month] + day-1;
IF ( (month > 2) AND ((year MOD 4 = 0) AND ((year MOD 100 <> 0) OR (year MOD 400 = 0))) ) THEN
days_from_1970 := days_from_1970 + 1; // + leap day, if year is leap year
END_IF;
// OUTPUT in s
l_unixtime := second + 60 * ( minute + 60 * (hour + 24 * days_from_1970) );
// if error return 0
IF sfc1_ret_val <> 0 THEN
Unixtime := 0;
ELSE
Unixtime := DINT_TO_DWORD(l_unixtime);
END_IF;
END_FUNCTION