fetching local time in Arduino

reza_neam
Posts: 12
Joined: Thu Dec 31, 2020 9:19 pm

fetching local time in Arduino

Postby reza_neam » Tue Mar 23, 2021 9:31 pm

Hi,

Currently, I am using pool.ntp.org to fetch the time. As you know it only returns the GMT time and if I want to convert it to the local time I need to know the offset.
I am wondering is there any way to find the offset based on the IP address of the ESP32 module?

lbernstone
Posts: 826
Joined: Mon Jul 22, 2019 3:20 pm

Re: fetching local time in Arduino

Postby lbernstone » Wed Mar 24, 2021 4:40 pm


reza_neam
Posts: 12
Joined: Thu Dec 31, 2020 9:19 pm

Re: fetching local time in Arduino

Postby reza_neam » Wed Mar 24, 2021 7:48 pm

Hi Ibernstone,

Thank you for your reply. I really found it thoughtful.
i found another API to that directly gives the offset value.
see
http://worldtimeapi.org/api/ip

reza_neam
Posts: 12
Joined: Thu Dec 31, 2020 9:19 pm

Re: fetching local time in Arduino

Postby reza_neam » Wed Mar 24, 2021 8:38 pm

So, I can minimize it to this

Code: Select all

  HTTPClient http;
  const char *ntpServer = "pool.ntp.org";
  const char *timeApiUrl = "http://worldtimeapi.org/api/ip";

  http.begin(timeApiUrl);
  int httpCode = http.GET();

  if (httpCode != 200)
  {
    printf("Unable to fetch the time info\r\n");
    configTime(0, 0, ntpServer);
    return;
  }
  String response = http.getString();
  long offset = response.substring(response.indexOf("\"raw_offset\":") + 13, response.indexOf(",\"timezone\":")).toFloat();
  http.end();

  configTime(offset, 0, ntpServer);

lbernstone
Posts: 826
Joined: Mon Jul 22, 2019 3:20 pm

Re: fetching local time in Arduino

Postby lbernstone » Wed Mar 24, 2021 9:13 pm

Hopefully someday we will be rid of the curse that is Daylight Savings Time and we can use a simple method to set time!

Who is online

Users browsing this forum: No registered users and 45 guests