Page 1 of 2

TimeLib : how to set time(nullptr) ?

PostPosted: Mon Dec 14, 2020 11:34 am
by alka79
In an old sketch, I use TimeLib with my own dayly NTP syncProvider function.
It works fine : now() returns epoch local time with DST adjustment.

However time(nullptr) always returns 0. I don't want another NTP sync for time().

How can I adjust the "internal" time() counter with the timestamp provided by now() ?

I have tried settimeofday() like this
Code: Select allSerial.println("time before " + String(time(nullptr)));
Serial.println("now " + String(now()));

struct timeval tv;
tv.tv_sec = now();

Serial.println("time after" + String(time(nullptr)));

without success :-( time(nullptr) always returns 0

Thanks for your help,

Re: TimeLib : how to set time(nullptr) ?

PostPosted: Wed Dec 16, 2020 5:07 am
by schufti
maybe have a look at the example in board package how they set internal time (RTC_UTC_TEST)
https://github.com/esp8266/Arduino/blob ... TZ-DST.ino

Re: TimeLib : how to set time(nullptr) ?

PostPosted: Wed Dec 16, 2020 7:10 am
by alka79
Thanks but that is what I don't want.
The "standard" configTime() uses it's own NTP connection. I'd like to avoid it.

In recent projects, I use this better approach.(and by the way, I prefer the example provided in a thread in this forum rather than the github example which is not really educational.)

For this older project, I would like minimal overload and directly set (or adjust) the internal time returned by time(nullptr) with the epoch timestamp I already have. Is that not possible ?

edit :
in the github example , they use this code to set manually from the RTC clok
Code: Select all  Serial.println("Manually setting some time from some RTC:");
  time_t rtc = RTC_UTC_TEST;
  timeval tv = { rtc, 0 };
  settimeofday(&tv, nullptr);

I have already tried this variant without success. time(nullptr) remains at 0.

Re: TimeLib : how to set time(nullptr) ?

PostPosted: Wed Dec 16, 2020 3:43 pm
by alka79
to be more precise, here is my test code

function for test purpose
Code: Select alltime_t myTimeCb()
  Serial.println("-- myTimeCb called. now is " + String(now()) + " [" +  timeStrDMYHMS(now()) +"]" );
  if (now() < 10) {
    return 1580598000; // 02.02.2020 00:00:00
  } else {
    return now();

in setup()
Code: Select all...
now() is initialized by my own NTP call
Serial.println("****Attempts to set internal time...");
Serial.println("Before=" + String(time(nullptr)) );

struct timeval tv;
tv.tv_sec = myTimeCb();
Serial.println("after=" + String(time(nullptr)) );

Serial.println("\nVariant from github example.\nBefore=" + String(time(nullptr)) );

time_t rtc = myTimeCb();
timeval tval = { rtc, 0 };
settimeofday(&tval, nullptr);
Serial.println("after=" + String(time(nullptr)) );

Serial output:
Code: Select all****Attempts to set internal time...
-- myTimeCb called. now is 1608154561 [16.12.20 21:36:01]

Variant from github example.
-- myTimeCb called. now is 1608154561 [16.12.20 21:36:01]