Skip to content

Manual Set Time not accounting for DST Properly (Fix attached)  #331

@Tshetrim

Description

@Tshetrim

File: https://github.com/rjwats/esp8266-react/blob/master/lib/framework/NTPSettingsService.cpp#L74

Hello, raising an issue with timezones and accounting for DST (Daylight Savings Time) on ESP32

For some reason, tm tm_isdst is set to a value (0 or 1) leading the conversion in mktime to not automatically calculate isdst and instead use that overriden value.

The impact was that when using this function, DST was not properly being accounted for leading to incorrect set time.

Solution:
Add:
tm.tm_isdst = -1;

Setting tm.tm_isdst to -1 before calling mktime causes it to do this calculation using the posix timezone (assuming its set) allowing for correct time setting.

See solution below:

void NTPSettingsService::configureTime(AsyncWebServerRequest* request, JsonVariant& json) {
  if (!sntp_enabled() && json.is<JsonObject>()) {
    struct tm tm = {0};
    tm.tm_isdst = -1;
    String timeLocal = json["local_time"];
    char* s = strptime(timeLocal.c_str(), "%Y-%m-%dT%H:%M:%S", &tm);
    if (s != nullptr) {
      time_t time = mktime(&tm);
      struct timeval now = {.tv_sec = time};
      settimeofday(&now, nullptr);
      AsyncWebServerResponse* response = request->beginResponse(200);
      request->send(response);
      return;
    }
  }
  AsyncWebServerResponse* response = request->beginResponse(400);
  request->send(response);
}

I realize this project is not maintained anymore but just wanted to leave this fix here incase anyone else encountered it (took me a bit to pindown the root cause).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions