ESPHome 2026.3.0-dev
Loading...
Searching...
No Matches
time.cpp
Go to the documentation of this file.
1#include "time.h" // NOLINT
2#include "helpers.h"
3
4#include <algorithm>
5
6namespace esphome {
7
8uint8_t days_in_month(uint8_t month, uint16_t year) {
9 static const uint8_t DAYS_IN_MONTH[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
10 if (month == 2 && (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0))
11 return 29;
12 return DAYS_IN_MONTH[month];
13}
14
15size_t ESPTime::strftime(char *buffer, size_t buffer_len, const char *format) {
16 struct tm c_tm = this->to_c_tm();
17 return ::strftime(buffer, buffer_len, format, &c_tm);
18}
19
20size_t ESPTime::strftime_to(std::span<char, STRFTIME_BUFFER_SIZE> buffer, const char *format) {
21 struct tm c_tm = this->to_c_tm();
22 size_t len = ::strftime(buffer.data(), buffer.size(), format, &c_tm);
23 if (len > 0) {
24 return len;
25 }
26 // Write "ERROR" to buffer on failure for consistent behavior
27 constexpr char error_str[] = "ERROR";
28 std::copy_n(error_str, sizeof(error_str), buffer.data());
29 return sizeof(error_str) - 1; // Length excluding null terminator
30}
31
32ESPTime ESPTime::from_c_tm(struct tm *c_tm, time_t c_time) {
33 ESPTime res{};
34 res.second = uint8_t(c_tm->tm_sec);
35 res.minute = uint8_t(c_tm->tm_min);
36 res.hour = uint8_t(c_tm->tm_hour);
37 res.day_of_week = uint8_t(c_tm->tm_wday + 1);
38 res.day_of_month = uint8_t(c_tm->tm_mday);
39 res.day_of_year = uint16_t(c_tm->tm_yday + 1);
40 res.month = uint8_t(c_tm->tm_mon + 1);
41 res.year = uint16_t(c_tm->tm_year + 1900);
42 res.is_dst = bool(c_tm->tm_isdst);
43 res.timestamp = c_time;
44 return res;
45}
46
47struct tm ESPTime::to_c_tm() {
48 struct tm c_tm {};
49 c_tm.tm_sec = this->second;
50 c_tm.tm_min = this->minute;
51 c_tm.tm_hour = this->hour;
52 c_tm.tm_mday = this->day_of_month;
53 c_tm.tm_mon = this->month - 1;
54 c_tm.tm_year = this->year - 1900;
55 c_tm.tm_wday = this->day_of_week - 1;
56 c_tm.tm_yday = this->day_of_year - 1;
57 c_tm.tm_isdst = this->is_dst;
58 return c_tm;
59}
60
61std::string ESPTime::strftime(const char *format) {
62 char buf[STRFTIME_BUFFER_SIZE];
63 size_t len = this->strftime_to(buf, format);
64 return std::string(buf, len);
65}
66
67std::string ESPTime::strftime(const std::string &format) { return this->strftime(format.c_str()); }
68
69// Helper to parse exactly N digits, returns false if not enough digits
70static bool parse_digits(const char *&p, const char *end, int count, uint16_t &value) {
71 value = 0;
72 for (int i = 0; i < count; i++) {
73 if (p >= end || *p < '0' || *p > '9')
74 return false;
75 value = value * 10 + (*p - '0');
76 p++;
77 }
78 return true;
79}
80
81// Helper to check for expected character
82static bool expect_char(const char *&p, const char *end, char expected) {
83 if (p >= end || *p != expected)
84 return false;
85 p++;
86 return true;
87}
88
89bool ESPTime::strptime(const char *time_to_parse, size_t len, ESPTime &esp_time) {
90 // Supported formats:
91 // YYYY-MM-DD HH:MM:SS (19 chars)
92 // YYYY-MM-DD HH:MM (16 chars)
93 // YYYY-MM-DD (10 chars)
94 // HH:MM:SS (8 chars)
95 // HH:MM (5 chars)
96
97 if (time_to_parse == nullptr || len == 0)
98 return false;
99
100 const char *p = time_to_parse;
101 const char *end = time_to_parse + len;
102 uint16_t v1, v2, v3, v4, v5, v6;
103
104 // Try date formats first (start with 4-digit year)
105 if (len >= 10 && time_to_parse[4] == '-') {
106 // YYYY-MM-DD...
107 if (!parse_digits(p, end, 4, v1))
108 return false;
109 if (!expect_char(p, end, '-'))
110 return false;
111 if (!parse_digits(p, end, 2, v2))
112 return false;
113 if (!expect_char(p, end, '-'))
114 return false;
115 if (!parse_digits(p, end, 2, v3))
116 return false;
117
118 esp_time.year = v1;
119 esp_time.month = v2;
120 esp_time.day_of_month = v3;
121
122 if (p == end) {
123 // YYYY-MM-DD (date only)
124 return true;
125 }
126
127 if (!expect_char(p, end, ' '))
128 return false;
129
130 // Continue with time part: HH:MM[:SS]
131 if (!parse_digits(p, end, 2, v4))
132 return false;
133 if (!expect_char(p, end, ':'))
134 return false;
135 if (!parse_digits(p, end, 2, v5))
136 return false;
137
138 esp_time.hour = v4;
139 esp_time.minute = v5;
140
141 if (p == end) {
142 // YYYY-MM-DD HH:MM
143 esp_time.second = 0;
144 return true;
145 }
146
147 if (!expect_char(p, end, ':'))
148 return false;
149 if (!parse_digits(p, end, 2, v6))
150 return false;
151
152 esp_time.second = v6;
153 return p == end; // YYYY-MM-DD HH:MM:SS
154 }
155
156 // Try time-only formats (HH:MM[:SS])
157 if (len >= 5 && time_to_parse[2] == ':') {
158 if (!parse_digits(p, end, 2, v1))
159 return false;
160 if (!expect_char(p, end, ':'))
161 return false;
162 if (!parse_digits(p, end, 2, v2))
163 return false;
164
165 esp_time.hour = v1;
166 esp_time.minute = v2;
167
168 if (p == end) {
169 // HH:MM
170 esp_time.second = 0;
171 return true;
172 }
173
174 if (!expect_char(p, end, ':'))
175 return false;
176 if (!parse_digits(p, end, 2, v3))
177 return false;
178
179 esp_time.second = v3;
180 return p == end; // HH:MM:SS
181 }
182
183 return false;
184}
185
187 this->timestamp++;
188 if (!increment_time_value(this->second, 0, 60))
189 return;
190
191 // second roll-over, increment minute
192 if (!increment_time_value(this->minute, 0, 60))
193 return;
194
195 // minute roll-over, increment hour
196 if (!increment_time_value(this->hour, 0, 24))
197 return;
198
199 // hour roll-over, increment day
201
202 if (increment_time_value(this->day_of_month, 1, days_in_month(this->month, this->year) + 1)) {
203 // day of month roll-over, increment month
204 increment_time_value(this->month, 1, 13);
205 }
206
207 uint16_t days_in_year = (this->year % 4 == 0) ? 366 : 365;
208 if (increment_time_value(this->day_of_year, 1, days_in_year + 1)) {
209 // day of year roll-over, increment year
210 this->year++;
211 }
212}
213
215 this->timestamp += 86400;
216
217 // increment day
219
220 if (increment_time_value(this->day_of_month, 1, days_in_month(this->month, this->year) + 1)) {
221 // day of month roll-over, increment month
222 increment_time_value(this->month, 1, 13);
223 }
224
225 uint16_t days_in_year = (this->year % 4 == 0) ? 366 : 365;
226 if (increment_time_value(this->day_of_year, 1, days_in_year + 1)) {
227 // day of year roll-over, increment year
228 this->year++;
229 }
230}
231
232void ESPTime::recalc_timestamp_utc(bool use_day_of_year) {
233 time_t res = 0;
234 if (!this->fields_in_range()) {
235 this->timestamp = -1;
236 return;
237 }
238
239 for (int i = 1970; i < this->year; i++)
240 res += (i % 4 == 0) ? 366 : 365;
241
242 if (use_day_of_year) {
243 res += this->day_of_year - 1;
244 } else {
245 for (int i = 1; i < this->month; i++)
246 res += days_in_month(i, this->year);
247 res += this->day_of_month - 1;
248 }
249
250 res *= 24;
251 res += this->hour;
252 res *= 60;
253 res += this->minute;
254 res *= 60;
255 res += this->second;
256 this->timestamp = res;
257}
258
260#ifdef USE_TIME_TIMEZONE
261 // Calculate timestamp as if fields were UTC
262 this->recalc_timestamp_utc(false);
263 if (this->timestamp == -1) {
264 return; // Invalid time
265 }
266
267 // Now convert from local to UTC by adding the offset
268 // POSIX: local = utc - offset, so utc = local + offset
269 const auto &tz = time::get_global_tz();
270
271 if (!tz.has_dst()) {
272 // No DST - just apply standard offset
273 this->timestamp += tz.std_offset_seconds;
274 return;
275 }
276
277 // Try both interpretations to match libc mktime() with tm_isdst=-1
278 // For ambiguous times (fall-back repeated hour), prefer standard time
279 // For invalid times (spring-forward skipped hour), libc normalizes forward
280 time_t utc_if_dst = this->timestamp + tz.dst_offset_seconds;
281 time_t utc_if_std = this->timestamp + tz.std_offset_seconds;
282
283 bool dst_valid = time::is_in_dst(utc_if_dst, tz);
284 bool std_valid = !time::is_in_dst(utc_if_std, tz);
285
286 if (dst_valid && std_valid) {
287 // Ambiguous time (repeated hour during fall-back) - prefer standard time
288 this->timestamp = utc_if_std;
289 } else if (dst_valid) {
290 // Only DST interpretation is valid
291 this->timestamp = utc_if_dst;
292 } else if (std_valid) {
293 // Only standard interpretation is valid
294 this->timestamp = utc_if_std;
295 } else {
296 // Invalid time (skipped hour during spring-forward)
297 // libc normalizes forward: 02:30 CST -> 08:30 UTC -> 03:30 CDT
298 // Using std offset achieves this since the UTC result falls during DST
299 this->timestamp = utc_if_std;
300 }
301#else
302 // No timezone support - treat as UTC
303 this->recalc_timestamp_utc(false);
304#endif
305}
306
308#ifdef USE_TIME_TIMEZONE
309 time_t now = ::time(nullptr);
310 const auto &tz = time::get_global_tz();
311 // POSIX offset is positive west, but we return offset to add to UTC to get local
312 // So we negate the POSIX offset
313 if (time::is_in_dst(now, tz)) {
314 return -tz.dst_offset_seconds;
315 }
316 return -tz.std_offset_seconds;
317#else
318 // No timezone support - no offset
319 return 0;
320#endif
321}
322
323bool ESPTime::operator<(const ESPTime &other) const { return this->timestamp < other.timestamp; }
324bool ESPTime::operator<=(const ESPTime &other) const { return this->timestamp <= other.timestamp; }
325bool ESPTime::operator==(const ESPTime &other) const { return this->timestamp == other.timestamp; }
326bool ESPTime::operator>=(const ESPTime &other) const { return this->timestamp >= other.timestamp; }
327bool ESPTime::operator>(const ESPTime &other) const { return this->timestamp > other.timestamp; }
328
329template<typename T> bool increment_time_value(T &current, uint16_t begin, uint16_t end) {
330 current++;
331 if (current >= end) {
332 current = begin;
333 return true;
334 }
335 return false;
336}
337
338} // namespace esphome
uint8_t month
Definition date_entity.h:1
uint16_t year
Definition date_entity.h:0
uint8_t second
uint8_t minute
uint8_t hour
bool is_in_dst(time_t utc_epoch, const ParsedTimezone &tz)
Check if a given UTC epoch falls within DST for the parsed timezone.
const ParsedTimezone & get_global_tz()
Get the global timezone.
Definition posix_tz.cpp:16
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
uint8_t days_in_month(uint8_t month, uint16_t year)
Definition time.cpp:8
std::string size_t len
Definition helpers.h:817
bool increment_time_value(T &current, uint16_t begin, uint16_t end)
Definition time.cpp:329
A more user-friendly version of struct tm from time.h.
Definition time.h:21
void increment_second()
Increment this clock instance by one second.
Definition time.cpp:186
static int32_t timezone_offset()
Definition time.cpp:307
uint8_t minute
minutes after the hour [0-59]
Definition time.h:30
void recalc_timestamp_utc(bool use_day_of_year=true)
Recalculate the timestamp field from the other fields of this ESPTime instance (must be UTC).
Definition time.cpp:232
bool operator<(const ESPTime &other) const
Definition time.cpp:323
uint8_t second
seconds after the minute [0-60]
Definition time.h:28
size_t strftime(char *buffer, size_t buffer_len, const char *format)
Convert this ESPTime struct to a null-terminated c string buffer as specified by the format argument.
Definition time.cpp:15
size_t strftime_to(std::span< char, STRFTIME_BUFFER_SIZE > buffer, const char *format)
Format time into a fixed-size buffer, returns length written.
Definition time.cpp:20
bool operator>(const ESPTime &other) const
Definition time.cpp:327
uint8_t hour
hours since midnight [0-23]
Definition time.h:32
time_t timestamp
unix epoch time (seconds since UTC Midnight January 1, 1970)
Definition time.h:46
void increment_day()
Increment this clock instance by one day.
Definition time.cpp:214
uint16_t day_of_year
day of the year [1-366]
Definition time.h:38
static ESPTime from_c_tm(struct tm *c_tm, time_t c_time)
Convert a C tm struct instance with a C unix epoch timestamp to an ESPTime instance.
Definition time.cpp:32
static bool strptime(const char *time_to_parse, size_t len, ESPTime &esp_time)
Convert a string to ESPTime struct as specified by the format argument.
Definition time.cpp:89
bool operator<=(const ESPTime &other) const
Definition time.cpp:324
bool operator==(const ESPTime &other) const
Definition time.cpp:325
void recalc_timestamp_local()
Recalculate the timestamp field from the other fields of this ESPTime instance assuming local fields.
Definition time.cpp:259
static constexpr size_t STRFTIME_BUFFER_SIZE
Buffer size required for strftime output.
Definition time.h:23
uint8_t day_of_month
day of the month [1-31]
Definition time.h:36
struct tm to_c_tm()
Convert this ESPTime instance back to a tm struct.
Definition time.cpp:47
uint16_t year
year
Definition time.h:42
bool fields_in_range() const
Check if all time fields of this ESPTime are in range.
Definition time.h:81
uint8_t month
month; january=1 [1-12]
Definition time.h:40
bool operator>=(const ESPTime &other) const
Definition time.cpp:326
uint8_t day_of_week
day of the week; sunday=1 [1-7]
Definition time.h:34
bool has_dst() const
Check if this timezone has DST rules.
Definition posix_tz.h:36
int32_t dst_offset_seconds
DST offset from UTC in seconds.
Definition posix_tz.h:31
int32_t std_offset_seconds
Standard time offset from UTC in seconds (positive = west)
Definition posix_tz.h:30
uint8_t end[39]
Definition sun_gtil2.cpp:17