Added 12 Hour Format 🚀 - #234
Conversation
|
Memory usage change @ 789bcf4
Click for full report table
Click for full report CSV |
|
I would strongly recommend rewriting this. This is a much simpler and efficient way to do it: int NTPClient::getHours12() const {
int h = this->getHours() % 12;
return (h == 0) ? 12 : h;
}
bool NTPClient::isPM() const {
return this->getHours() >= 12;
}
String NTPClient::getFormattedTime12() const {
char buffer[12]; // "HH:MM:SS AM\0"
int h12 = getHours12();
int m = getMinutes();
int s = getSeconds();
const char* period = isPM() ? "PM" : "AM";
snprintf(buffer, sizeof(buffer), "%02d:%02d:%02d %s", h12, m, s, period);
return String(buffer);
}Modulo makes the hour calculation simpler, snprintf formats the string from inputs and is much more efficient than concatenating strings. |
My implementation follows the structure of the 24-hour implementation: String NTPClient::getFormattedTime() const {
unsigned long rawTime = this->getEpochTime();
unsigned long hours = (rawTime % 86400L) / 3600;
String hoursStr = hours < 10 ? "0" + String(hours) : String(hours);
unsigned long minutes = (rawTime % 3600) / 60;
String minuteStr = minutes < 10 ? "0" + String(minutes) : String(minutes);
unsigned long seconds = rawTime % 60;
String secondStr = seconds < 10 ? "0" + String(seconds) : String(seconds);
return hoursStr + ":" + minuteStr + ":" + secondStr;
}Do you think a major refactoring is needed? The options are:
|
|
Sorry, I didn't notice that it was based off the existing code. However, I don't know how much more/less flash including that uses, and I also am not sure if the efficiency gains are going to be that noticeable. I mean it's only a few bytes of strings. Not sure if we should prioritize size or speed, but I think it's likely 1 extra KB is not worth a minor speed improvement. If we really want fast & light, maybe we use something like this: String NTPClient::getFormattedTime12() const {
char buffer[12]; // "HH:MM:SS AM\0"
int h12 = getHours12();
int m = getMinutes();
int s = getSeconds();
buffer[0] = (h12 / 10) + '0';
buffer[1] = (h12 % 10) + '0';
buffer[2] = ':';
buffer[3] = (m / 10) + '0';
buffer[4] = (m % 10) + '0';
buffer[5] = ':';
buffer[6] = (s / 10) + '0';
buffer[7] = (s % 10) + '0';
buffer[8] = ' ';
bool pm = isPM();
buffer[9] = pm ? 'P' : 'A';
buffer[10] = 'M';
buffer[11] = '\0';
return String(buffer);
}Not particularly pretty, but it doesn't use Strings nor snprintf. For something like a static format template this is much smaller and faster. |
|
@Randomblock1 I followed the existing pattern in |
|
@per1234 news? |
Close #222 using the following code: