NTPClient
NTPClient copied to clipboard
getFormattedTime does not give date+time string
Hi,
in version 3.2 getFormattedTime gives only the time, e.g. 17:35:27 and not the complete String including the date, e.g. 2021-05-16T17:35:27Z.
Anyway to get the date?
cheers .d
Get this issue too - now using ESP8266 Core 3.0.0. Great to get a fix!
Not only does getFormattedTime() not give the date, the time is often invalid, because the digits for minutes are reversed! I get for example: 06:75, 06:85, 06:95 instead of 06:57, 06:58, 06:59!
On Arduino 1.8.15/ESP32 v2.0.0-rc-1 It could be a problem with the String() constructor from unsigned long, because I don't see anything weird in your code.
Indeed it is. Look at the output of this code:
void setup() {
Serial.begin(115200);
delay(100);
for(unsigned long ul = 0; ul < 60; ul++) {
Serial.println(String(ul));
}
}
void loop() {
}
it prints:
0
1
2
3
4
5
6
7
8
9
01
11
21
31
41
51
61
71
81
91
02
12
22
etc.
It's hilarious! I will post it on the ESP32 thread (if not already done so)
The problem can be fixed in your getFormattedTime() code to change the type of the variables hours, minutes and seconds from unsigned long to unsigned short, which is more than enough for those values [0-59].
String NTPClient::getFormattedTime() const {
unsigned long rawTime = this->getEpochTime();
unsigned short hours = (rawTime % 86400L) / 3600;
String hoursStr = hours < 10 ? "0" + String(hours) : String(hours);
unsigned short minutes = (rawTime % 3600) / 60;
String minuteStr = minutes < 10 ? "0" + String(minutes) : String(minutes);
unsigned short seconds = rawTime % 60;
String secondStr = seconds < 10 ? "0" + String(seconds) : String(seconds);
return hoursStr + ":" + minuteStr + ":" + secondStr;
}
in version 3.2 getFormattedTime gives only the time, e.g. 17:35:27 and not the complete String including the date, e.g. 2021-05-16T17:35:27Z.
Anyway to get the date?
use getFomattedDate() from this fork: https://github.com/taranais/NTPClient