From 6dd0020bf6f9c555a037cd4c681a6c9e934f5e29 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Fri, 17 Oct 2025 09:39:51 -1000 Subject: [PATCH] [api][time] Refactor timezone update logic for cleaner code --- esphome/components/api/api_connection.cpp | 9 ++------- esphome/components/time/real_time_clock.h | 8 ++++++++ 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/esphome/components/api/api_connection.cpp b/esphome/components/api/api_connection.cpp index 1f3456a205..39bcb83cfb 100644 --- a/esphome/components/api/api_connection.cpp +++ b/esphome/components/api/api_connection.cpp @@ -1081,13 +1081,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