#include <WiFi.h>
#include <time.h>
// WiFi credentials
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
// NTP server and timezone
const char* ntpServer = "pool.ntp.org";
const long gmtOffset_sec = 0; // Adjust for your timezone
const int daylightOffset_sec = 0;
// 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 NTP time and a past time
void calculateDurationFromNTP(const char *pastTimeStr) {
struct tm pastTm = parseTime(pastTimeStr); // Parse past time
time_t past = mktime(&pastTm);
if (past == -1) {
Serial.println("Error: Invalid past time.");
return;
}
// Get current time from NTP
struct tm currentTm;
if (!getLocalTime(¤tTm)) {
Serial.println("Error: Failed to obtain current time.");
return;
}
time_t current = mktime(¤tTm);
Serial.println(current);
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);
WiFi.begin("Wokwi-GUEST", "", 6);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("\nConnected to WiFi");
// Initialize NTP
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
// Example usage with NTP
calculateDurationFromNTP("2024-12-25 11:13:46"); // Past time
//"%Y-%m-%d %H:%M:%S"
}
void loop() {
// Your code here
}