Hi there,
I've been trying to work out how to get the time to automatically adjust in line with UK Daylight Savings Time.
I found some code, that gives me the time but it seems to do it on a temporary basis. For example, in the code below, I reference a field called "local" which displays the correct hour value. However, if I try to print the value a second time, it goes back to Epoch time.
I used to get the time by using the get.hours command but that is not working as expected.
Is there an easy way to get the uk local time without faffing around too much ?
Many thanks, in advance
TK
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <NTPClient.h>
#include <Timezone.h>
// Define your WiFi credentials
const char* ssid = "SSID";
const char* password = "Password";
// Define your timezone offset and whether it observes DST
TimeChangeRule BST = {"BST", Last, Sun, Mar, 1, 60}; // British Summer Time
TimeChangeRule GMT = {"GMT", Last, Sun, Oct, 2, 0}; // Greenwich Mean Time
Timezone UK(BST, GMT);
// Define NTP client and time server settings
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org");
void setup() {
Serial.begin(115200);
delay(1000);
// Connect to WiFi
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected.");
// Initialize NTP client
timeClient.begin();
timeClient.setTimeOffset(0); // Set time offset to UTC (NTP servers return UTC time)
}
void loop() {
// Update time from NTP server
timeClient.update();
unsigned long epochTime = timeClient.getEpochTime(); // Get Unix timestamp from NTP server
time_t utc = epochTime;
time_t local = UK.toLocal(utc); // Convert UTC time to local time (DST adjusted)
int now_hour = timeClient.getHours(); // This is the command I usually use but it's become inaccurate as of a couple of days ago, when the clocks changed.
Serial.print("now_hour ");
Serial.println(now_hour);
// Print the DST adjusted local time
Serial.print("DST Adjusted Local time: ");
digitalClockDisplay(local);
Serial.print("DST Adjusted Local time TWO: ");
Serial.println(local); // The line above prints the correct value, this line prints the Epoch value again!
delay(1000);
}
void digitalClockDisplay(time_t t) {
static char local[20];
sprintf(local, "%02d:%02d:%02d", hour(t), minute(t), second(t));
Serial.println(local);
}