Get current time using ESP32 and gettimeofday() on Arduino IDE

Hi,

I am using a ESP32 module and am coding in Arduino IDE. I was able to get the current date and time by polling NTP servers and using struct tm and getLocalTime() function. However, the time I receive back from the NTP server doing so is in seconds and I would like to have the time in milliseconds or microseconds precision.

After searching on the internet how I could do this, I found people recommend using struct timeval and function gettimeofday() instead. So I modified my code and tried it out.
But the output I get is something like: TimeVal-sec = 5 TimeVal-usec = 792802

It should return the number of seconds since January 1st 1970, which I don't get...

I'll post my code below. Hopefully someone can help me with this!

PS: I'm on Windows

void setup()
{
  Serial.begin(9600);

  //connect to WiFi
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
  Serial.println(" CONNECTED");

  //initialize NTP client and get the time
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer1, ntpServer2, ntpServer3);
  //printLocalTime();

  //disconnect WiFi as it's no longer needed
  WiFi.disconnect(true);
  WiFi.mode(WIFI_OFF);
}


void printLocalTime()
{
  struct timeval tv;
  if (gettimeofday(&tv, NULL)!= 0) {
    Serial.println("Failed to obtain time");
    return;
  }
  Serial.print("TimeVal-sec = ");
  Serial.print(tv.tv_sec);
  Serial.print(" ");
  Serial.print("TimeVal-usec = ");
  Serial.print(tv.tv_usec);
  Serial.println();
}

https://esp32.com/viewtopic.php?t=5288
Perhaps that is the answer to your question.

I developed an ntp based esp8266 speaking clock which I got to a precision of around one hundredth of a second.
Getting the time stamp is only one part of the problem. Since the time library and RTC have a granularity of one second, it was important to update the time exactly on the seconds rollover. For example, if the ntp timestamp is 23:48:35.4 , you have to schedule an update of the RTC in 0.6 seconds for the time 23:48:36.

The project is here and maybe you find something useful:

Because it was an audio application, it was important that there was no blocking code which could cause jitter so the ntp fetch part is non blocking. Most ntp libraries send an ntp request then wait in a blocking loop for the reply (or a timeout).

It is not a full ntp client and makes no attempt to statistically compensate for network latency.

Idahowalker:
Perhaps that is the answer to your question.

I've seen this already and tried it but still the same result...
Is anything wrong with my code?