From f286bc57f3fda499f270c37e4390c2189a3980ec Mon Sep 17 00:00:00 2001 From: Eyal <109809+eyal0@users.noreply.github.com> Date: Mon, 1 Sep 2025 22:45:25 -0600 Subject: [PATCH] [core] Fix timezone offset calculation (#10426) --- esphome/core/time.cpp | 26 ++++++-------------------- 1 file changed, 6 insertions(+), 20 deletions(-) diff --git a/esphome/core/time.cpp b/esphome/core/time.cpp index f9652b5329..fe6f50158c 100644 --- a/esphome/core/time.cpp +++ b/esphome/core/time.cpp @@ -203,27 +203,13 @@ void ESPTime::recalc_timestamp_local() { } int32_t ESPTime::timezone_offset() { - int32_t offset = 0; time_t now = ::time(nullptr); - auto local = ESPTime::from_epoch_local(now); - auto utc = ESPTime::from_epoch_utc(now); - bool negative = utc.hour > local.hour && local.day_of_year <= utc.day_of_year; - - if (utc.minute > local.minute) { - local.minute += 60; - local.hour -= 1; - } - offset += (local.minute - utc.minute) * 60; - - if (negative) { - offset -= (utc.hour - local.hour) * 3600; - } else { - if (utc.hour > local.hour) { - local.hour += 24; - } - offset += (local.hour - utc.hour) * 3600; - } - return offset; + struct tm local_tm = *::localtime(&now); + local_tm.tm_isdst = 0; // Cause mktime to ignore daylight saving time because we want to include it in the offset. + time_t local_time = mktime(&local_tm); + struct tm utc_tm = *::gmtime(&now); + time_t utc_time = mktime(&utc_tm); + return static_cast(local_time - utc_time); } bool ESPTime::operator<(const ESPTime &other) const { return this->timestamp < other.timestamp; }