diff --git a/esphome/components/sun/text_sensor/sun_text_sensor.h b/esphome/components/sun/text_sensor/sun_text_sensor.h index 3474e35fc3..9345a32223 100644 --- a/esphome/components/sun/text_sensor/sun_text_sensor.h +++ b/esphome/components/sun/text_sensor/sun_text_sensor.h @@ -30,11 +30,7 @@ class SunTextSensor : public text_sensor::TextSensor, public PollingComponent { char buf[ESPTime::STRFTIME_BUFFER_SIZE]; size_t len = res->strftime_to(buf, this->format_.c_str()); - if (len > 0) { - this->publish_state(buf, len); - } else { - this->publish_state("ERROR"); - } + this->publish_state(buf, len); } void dump_config() override; diff --git a/esphome/core/time.cpp b/esphome/core/time.cpp index 98dd77c61f..38ef6b62f6 100644 --- a/esphome/core/time.cpp +++ b/esphome/core/time.cpp @@ -1,6 +1,7 @@ #include "time.h" // NOLINT #include "helpers.h" +#include #include namespace esphome { @@ -19,7 +20,14 @@ size_t ESPTime::strftime(char *buffer, size_t buffer_len, const char *format) { size_t ESPTime::strftime_to(std::span buffer, const char *format) { struct tm c_tm = this->to_c_tm(); - return ::strftime(buffer.data(), buffer.size(), format, &c_tm); + size_t len = ::strftime(buffer.data(), buffer.size(), format, &c_tm); + if (len > 0) { + return len; + } + // Write "ERROR" to buffer on failure for consistent behavior + constexpr char ERROR_STR[] = "ERROR"; + std::copy_n(ERROR_STR, sizeof(ERROR_STR), buffer.data()); + return sizeof(ERROR_STR) - 1; // Length excluding null terminator } ESPTime ESPTime::from_c_tm(struct tm *c_tm, time_t c_time) { @@ -54,10 +62,7 @@ struct tm ESPTime::to_c_tm() { std::string ESPTime::strftime(const char *format) { char buf[STRFTIME_BUFFER_SIZE]; size_t len = this->strftime_to(buf, format); - if (len > 0) { - return std::string(buf, len); - } - return "ERROR"; + return std::string(buf, len); } std::string ESPTime::strftime(const std::string &format) { return this->strftime(format.c_str()); } diff --git a/esphome/core/time.h b/esphome/core/time.h index 93bae194c3..f6f1d57dbb 100644 --- a/esphome/core/time.h +++ b/esphome/core/time.h @@ -47,9 +47,10 @@ struct ESPTime { */ size_t strftime(char *buffer, size_t buffer_len, const char *format); - /** Format time into a fixed-size buffer, returns length written (0 on error). + /** Format time into a fixed-size buffer, returns length written. * * This is the preferred method for avoiding heap allocations. The buffer size is enforced at compile-time. + * On format error, writes "ERROR" to the buffer and returns 5. * @see https://www.gnu.org/software/libc/manual/html_node/Formatting-Calendar-Time.html#index-strftime */ size_t strftime_to(std::span buffer, const char *format);