#include <time.h>
#include <string.h>
// Parse a time string "YYYY-MM-DD HH:MM:SS" into struct tm
struct tm parseTime(const char *timeStr) {
struct tm t = {0};
sscanf(timeStr, "%d-%d-%d %d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec);
t.tm_year -= 1900; // Adjust year
t.tm_mon -= 1; // Adjust month
return t;
}
// Calculate duration between two time strings
void calculateDuration(const char *currentTimeStr, const char *pastTimeStr) {
struct tm currentTm = parseTime(currentTimeStr); // Temporary variable for current time
struct tm pastTm = parseTime(pastTimeStr); // Temporary variable for past time
time_t current = mktime(¤tTm);
time_t past = mktime(&pastTm);
if (current == -1 || past == -1) {
Serial.println("Error: Invalid time conversion.");
return;
}
int seconds = difftime(current, past);
Serial.printf("Duration: %d days, %d hours, %d minutes, %d seconds\n",
seconds / 86400, (seconds % 86400) / 3600, (seconds % 3600) / 60, seconds % 60);
}
void setup() {
Serial.begin(115200);
calculateDuration("2024-12-27 12:00:00", "2023-12-20 14:30:00");
}
void loop() {
// Your code here
}