Skip to content

Commit e1d034a

Browse files
committed
use mktime to compute unix timestamp
1 parent 8efd7f4 commit e1d034a

File tree

1 file changed

+23
-6
lines changed

1 file changed

+23
-6
lines changed

src/TimeUtils.h

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#include <Arduino.h>
2+
#include <time.h>
23

34
/**
45
* @class Time
@@ -91,19 +92,35 @@ class Time {
9192
* @return The time in UNIX timestamp format.
9293
*/
9394
String getUNIXTimestampString() {
94-
// Simple conversion to UNIX timestamp, not accounting for leap years or time zones
95-
long timestamp = second + minute*60 + hour*3600 + day*86400 + (month-1)*2629743 + (year-1970)*31556926;
96-
return String(timestamp);
95+
return String(getUNIXTimestamp());
9796
}
9897

9998
/**
10099
* Returns the time in UNIX timestamp format.
101100
* @return The time in UNIX timestamp format.
102101
*/
103102
unsigned long getUNIXTimestamp() {
104-
// Simple conversion to UNIX timestamp, not accounting for leap years or time zones
105-
unsigned long timestamp = second + minute*60 + hour*3600 + day*86400 + (month-1)*2629743 + (year-1970)*31556926;
106-
return timestamp;
103+
struct tm t =
104+
{
105+
0 /* tm_sec */,
106+
0 /* tm_min */,
107+
0 /* tm_hour */,
108+
0 /* tm_mday */,
109+
0 /* tm_mon */,
110+
0 /* tm_year */,
111+
0 /* tm_wday */,
112+
0 /* tm_yday */,
113+
0 /* tm_isdst */
114+
};
115+
t.tm_mon = month - 1;
116+
t.tm_mday = day;
117+
t.tm_year = year - 1900;
118+
t.tm_hour = hour;
119+
t.tm_min = minute;
120+
t.tm_sec = second;
121+
t.tm_isdst = -1;
122+
123+
return mktime(&t);
107124
}
108125

109126
/**

0 commit comments

Comments
 (0)