diff --git a/esphome/components/api/api_connection.cpp b/esphome/components/api/api_connection.cpp index ea1e130092..7dfefedd54 100644 --- a/esphome/components/api/api_connection.cpp +++ b/esphome/components/api/api_connection.cpp @@ -1082,13 +1082,8 @@ void APIConnection::on_get_time_response(const GetTimeResponse &value) { homeassistant::global_homeassistant_time->set_epoch_time(value.epoch_seconds); #ifdef USE_TIME_TIMEZONE if (value.timezone_len > 0) { - const std::string ¤t_tz = homeassistant::global_homeassistant_time->get_timezone(); - // Compare without allocating a string - if (current_tz.length() != value.timezone_len || - memcmp(current_tz.c_str(), value.timezone, value.timezone_len) != 0) { - homeassistant::global_homeassistant_time->set_timezone( - std::string(reinterpret_cast(value.timezone), value.timezone_len)); - } + homeassistant::global_homeassistant_time->set_timezone(reinterpret_cast(value.timezone), + value.timezone_len); } #endif } diff --git a/esphome/components/time/real_time_clock.h b/esphome/components/time/real_time_clock.h index 4b98a88975..7e60bbd234 100644 --- a/esphome/components/time/real_time_clock.h +++ b/esphome/components/time/real_time_clock.h @@ -27,6 +27,14 @@ class RealTimeClock : public PollingComponent { this->apply_timezone_(); } + /// Set the time zone from raw buffer, only if it differs from the current one. + void set_timezone(const char *tz, size_t len) { + if (this->timezone_.length() != len || memcmp(this->timezone_.c_str(), tz, len) != 0) { + this->timezone_.assign(tz, len); + this->apply_timezone_(); + } + } + /// Get the time zone currently in use. std::string get_timezone() { return this->timezone_; } #endif