I use NTP to retrieve the current UTC datetime and to set epoch of the RTC.
The problem is when I want to get the RTC value.
If I set RTC epoch with NTP as local time:
- localtime from RTC epoch gives UTC datetime.
- gmtime from RTC epoch gives UTC datetime minus timezone offset.
This is the test code:
Code: Select all
// Time zone
setenv("TZ", "CET-1CEST,M3.5.0,M10.5.0/3", 1); // Europe/Paris
tzset();
// NTP
ntp.setPoolServerName("192.168.2.1");
ntp.begin();
if (ntp.forceUpdate()) {
Serial.println(ntp.getFormattedTime());
}
ntp.end();
time_t local, utc;
{
time_t epoch = ntp.getEpochTime();
char buffer[80];
// Local
struct tm ts = *localtime(&epoch);
strftime(buffer, sizeof(buffer), "LOC %a %Y-%m-%d %H:%M:%S", &ts);
Serial.print(buffer);
Serial.println();
local = mktime(&ts);
// UTC
ts = *gmtime(&epoch);
strftime(buffer, sizeof(buffer), "UTC %a %Y-%m-%d %H:%M:%S", &ts);
Serial.print(buffer);
Serial.println();
utc = mktime(&ts);
}
// RTC
rtc.begin();
{
rtc.setEpoch(local); // Local time
time_t epoch = rtc.getEpoch();
struct tm ts;
char buffer[80];
ts = *localtime(&epoch); // Not local, UTC!
strftime(buffer, sizeof(buffer), "LOC %a %Y-%m-%d %H:%M:%S", &ts);
Serial.print(buffer);
Serial.println();
ts = *gmtime(&epoch); // Not UTC!
strftime(buffer, sizeof(buffer), "UTC %a %Y-%m-%d %H:%M:%S", &ts);
Serial.print(buffer);
Serial.println();
}
{
rtc.setEpoch(utc); // UTC time
uint32_t ss = rtc.getSubSeconds();
time_t epoch = rtc.getEpoch();
struct tm ts;
char buffer[80];
ts = *localtime(&epoch); // Not local, not UTC!
strftime(buffer, sizeof(buffer), "LOC %a %Y-%m-%d %H:%M:%S", &ts);
Serial.print(buffer);
Serial.println();
ts = *gmtime(&epoch); // Not local, not UTC!
strftime(buffer, sizeof(buffer), "UTC %a %Y-%m-%d %H:%M:%S", &ts);
Serial.print(buffer);
Serial.println();
}
Code: Select all
15:47:50
LOC Mon 2021-11-15 16:47:50
UTC Mon 2021-11-15 15:47:50
LOC Mon 2021-11-15 15:47:50
UTC Mon 2021-11-15 14:47:50
LOC Mon 2021-11-15 14:47:50
UTC Mon 2021-11-15 13:47:50