0

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

Here are more information to 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 informations to be displayed on an 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?

1

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() {
}
  • note you might need to divide the timestamp by 1000 if it includes ms, like JS's Dates for example. – dandavis Feb 14 at 18:31
  • @dandavis, I took the sample JSON from the openweathermap site – Juraj Feb 14 at 18:39
  • For sure, I'm just pointing out that there's two "epoc"s to be aware of from web services, in general. – dandavis Feb 14 at 18:41
  • For this example, it's not necessary to divide by 1000. Thank you very much for the help :) – imax10000 Feb 14 at 18:43
  • @Juraj I have one more question to this topic: Can TimeLib also convert EPOCH timestamps to day names?(Monday, etc.) – imax10000 Feb 15 at 10:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.