1 | #include <NTPClient.h>
|
2 | #include <WiFiUdp.h>
|
3 |
|
4 | WiFiUDP ntpUDP;
|
5 | NTPClient timeClient(ntpUDP, "pool.ntp.org");
|
6 |
|
7 |
|
8 | String weekDays[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
|
9 |
|
10 | String months[12] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
|
11 |
|
12 | void NTP_setup()
|
13 | {
|
14 | timeClient.begin();
|
15 | timeClient.setTimeOffset(3600);
|
16 | }
|
17 |
|
18 | String NTP_getDateTime()
|
19 | {
|
20 | timeClient.update();
|
21 |
|
22 | time_t epochTime = timeClient.getEpochTime();
|
23 | Serial.print("Epoch Time: ");
|
24 | Serial.println(epochTime);
|
25 |
|
26 | String formattedTime = timeClient.getFormattedTime();
|
27 | Serial.print("Formatted Time: ");
|
28 | Serial.println(formattedTime);
|
29 |
|
30 | int currentHour = timeClient.getHours();
|
31 | Serial.print("Hour: ");
|
32 | Serial.println(currentHour);
|
33 |
|
34 | int currentMinute = timeClient.getMinutes();
|
35 | Serial.print("Minutes: ");
|
36 | Serial.println(currentMinute);
|
37 |
|
38 | int currentSecond = timeClient.getSeconds();
|
39 | Serial.print("Seconds: ");
|
40 | Serial.println(currentSecond);
|
41 |
|
42 | String weekDay = weekDays[timeClient.getDay()];
|
43 | Serial.print("Week Day: ");
|
44 | Serial.println(weekDay);
|
45 |
|
46 | struct tm *ptm = gmtime((time_t *)&epochTime);
|
47 |
|
48 | int monthDay = ptm->tm_mday;
|
49 | Serial.print("Month day: ");
|
50 | Serial.println(monthDay);
|
51 |
|
52 | int currentMonth = ptm->tm_mon + 1;
|
53 | Serial.print("Month: ");
|
54 | Serial.println(currentMonth);
|
55 |
|
56 | String currentMonthName = months[currentMonth - 1];
|
57 | Serial.print("Month name: ");
|
58 | Serial.println(currentMonthName);
|
59 |
|
60 | int currentYear = ptm->tm_year + 1900;
|
61 | Serial.print("Year: ");
|
62 | Serial.println(currentYear);
|
63 |
|
64 | String currentDate = String(currentYear) + "-" + String(currentMonth) + "-" + String(monthDay);
|
65 | Serial.print("Current date: ");
|
66 | Serial.println(currentDate);
|
67 |
|
68 | Serial.println("");
|
69 |
|
70 | return timeClient.getFormattedTime();
|
71 | }
|