4

I have a question on how to convert EPOCH timestamps, which I receive as char*, into DD.MM.YYYY and HH:MM:SS format separately?

Here is more information on my Arduino project: The Arduino is receiving through an ESP8266 module three different EPOCH timestamps from the OpenWeatherMap API for sunrise, sunset and the current date. I want these 3 pieces of information to be displayed on a 1,3" OLED display, the date in DD.MM.YYYY and the other two timestamps in HH:MM format.

I was looking in several time libraries like TimeLib and RTC for a solution, but I wasn't able to find one.

That's my code fragment on receiving the timestamps:

DynamicJsonBuffer jsonBuffer(4096);
JsonObject& root = jsonBuffer.parseObject(client);

const char* date = root["dt"]; const char* sunrise = root["sys"]["sunrise"]; const char* sunset = root["sys"]["sunset"];

How to convert those timestamps?

Rohit Gupta
  • 618
  • 2
  • 5
  • 18
imax10000
  • 43
  • 1
  • 1
  • 3

2 Answers2

3

Epoch are seconds from 1970-01-01. Get it from JSON as unsigned long. They are a number in the returned JSON (no ")

from https://openweathermap.org/ doc:

"sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049},


to convert it to string with TimeLib.h:

#include <TimeLib.h>
#include <ArduinoJson.h>

void setup() {

  Serial.begin(115200);

  const char* json = "{\"country\":\"JP\",\"sunrise\":1369769524,\"sunset\":1369821049}";

  DynamicJsonBuffer jsonBuffer;
  JsonObject& root = jsonBuffer.parseObject(json);

  unsigned long t = root["sunrise"];

  char buff[32];
  sprintf(buff, "%02d.%02d.%02d %02d:%02d:%02d", day(t), month(t), year(t), hour(t), minute(t), second(t));

  Serial.println(buff);
}

void loop() {
}
Juraj
  • 18,264
  • 4
  • 31
  • 49
0

I'm was having a similar challenge with my custom Wifi library m_wifi..cpp for the ESP32 ( see here )

After reading and googling I ended up coding the solution below:

ESP32Time rtc(0);
long int epochTime;
...

rtc.setTime( epochTime ); Serial.println( rtc.getDateTime(true) );

Miguel Tomás
  • 219
  • 1
  • 9