#include <WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org");
unsigned long lastUpdate = 0;
void setup() {
Serial.begin(115200);
// Connect to WiFi
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected");
// Initialize NTP Client
timeClient.begin();
timeClient.setTimeOffset(0); // GMT offset in seconds
// Wait for the time to be updated
while (!timeClient.update()) {
timeClient.forceUpdate();
}
// Print GMT time
Serial.print("GMT time: ");
Serial.println(timeClient.getFormattedTime());
// Print Epoch time
Serial.print("Epoch time: ");
Serial.println(timeClient.getEpochTime());
lastUpdate = millis();
}
void loop() {
// Update time every 2 minutes
if (millis() - lastUpdate > 120000) {
if (timeClient.update()) {
Serial.print("GMT time: ");
Serial.println(timeClient.getFormattedTime());
Serial.print("Epoch time: ");
Serial.println(timeClient.getEpochTime());
lastUpdate = millis();
}
}
delay(1000);
}
// #include <WiFi.h>
// #include <NTPClient.h>
// #include <WiFiUdp.h>
// const char* ssid = "Wokwi-GUEST";
// const char* password = "";
// WiFiUDP ntpUDP;
// NTPClient timeClient(ntpUDP, "pool.ntp.org");
// unsigned long lastUpdate = 0;
// void setup() {
// Serial.begin(115200);
// // Connect to WiFi
// WiFi.begin(ssid, password);
// Serial.print("Connecting to WiFi");
// while (WiFi.status() != WL_CONNECTED) {
// delay(500);
// Serial.print(".");
// }
// Serial.println("\nWiFi connected");
// // Initialize NTP Client
// timeClient.begin();
// timeClient.setTimeOffset(25200); // 7 * 60 * 60 (GMT+7 offset in seconds)
// // Wait for the time to be updated
// while (!timeClient.update()) {
// timeClient.forceUpdate();
// }
// // Print Jakarta time (GMT+7)
// Serial.print("Jakarta time (GMT+7): ");
// Serial.println(timeClient.getFormattedTime());
// // Print Epoch time
// Serial.print("Epoch time: ");
// Serial.println(timeClient.getEpochTime());
// lastUpdate = millis();
// }
// void loop() {
// // Update time every 2 minutes
// if (millis() - lastUpdate > 120000) {
// if (timeClient.update()) {
// Serial.print("Jakarta time (GMT+7): ");
// Serial.println(timeClient.getFormattedTime());
// Serial.print("Epoch time: ");
// Serial.println(timeClient.getEpochTime() + 25200); // Add offset
// lastUpdate = millis();
// }
// }
// delay(1000);
// }