{"id":66810,"date":"2018-07-21T22:08:36","date_gmt":"2018-07-21T22:08:36","guid":{"rendered":"http:\/\/randomnerdtutorials.com\/?p=66810"},"modified":"2024-06-12T14:51:25","modified_gmt":"2024-06-12T14:51:25","slug":"esp32-ntp-client-date-time-arduino-ide","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/esp32-ntp-client-date-time-arduino-ide\/","title":{"rendered":"Getting Date and Time with ESP32 on Arduino IDE (NTP Client)"},"content":{"rendered":"\n<p>In this tutorial we\u2019ll show you how to get date and time using the ESP32 and Arduino IDE. Getting date and time is especially useful in data logging to timestamp your readings. If your ESP32 project has access to the Internet, you can get date and time using Network Time Protocol (NTP) &#8211; you don&#8217;t need any additional hardware.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" width=\"1200\" height=\"675\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/07\/NTPClient-ESP32-featured.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-67887\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/07\/NTPClient-ESP32-featured.jpg?w=1280&amp;quality=100&amp;strip=all&amp;ssl=1 1280w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/07\/NTPClient-ESP32-featured.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/07\/NTPClient-ESP32-featured.jpg?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/07\/NTPClient-ESP32-featured.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n<p class=\"rntbox rntcred\"><strong>Note: <\/strong> there&#8217;s an easier and updated guide to get date and time with the ESP32 with the pre-installed time.h library: <a href=\"https:\/\/randomnerdtutorials.com\/esp32-date-time-ntp-client-server-arduino\/\">ESP32 NTP Client-Server: Get Date and Time (Arduino IDE)<\/a>.<\/p>\n\n\n\n<p>Before proceeding with this tutorial you should have the ESP32 add-on installed in your Arduino IDE. Follow one of the following tutorials to install the ESP32 on the Arduino IDE, if you haven\u2019t already.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/installing-esp32-arduino-ide-2-0\/\" title=\"\">Installing ESP32 Board in Arduino IDE 2 (Windows, Mac OS X, Linux)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/installing-esp8266-nodemcu-arduino-ide-2-0\/\" title=\"\">Installing ESP8266 NodeMCU Board in Arduino IDE 2 (Windows, Mac OS X, Linux)<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">NTP Client Library<\/h2>\n\n\n\n<p class=\"rntbox rntcred\"><strong>IMPORTANT<\/strong>: we&#8217;re not using the default NTPClient library. To follow this tutorial you need to install the library we recommend using the following steps.<\/p>\n\n\n\n<p>The easiest way to get date and time from an NTP server is using an NTP Client library. For that we\u2019ll be using the <a href=\"https:\/\/github.com\/taranais\/NTPClient\" target=\"_blank\" rel=\"noreferrer noopener\">NTP Client library forked by Taranais<\/a>. Follow the next steps to install this library in your Arduino IDE:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><a href=\"https:\/\/github.com\/taranais\/NTPClient\/archive\/master.zip\">Click here to download the NTP Client library<\/a>. You should have a .zip folder in your <em>Downloads<\/em><\/li>\n\n\n\n<li>In your Arduino IDE, go to <strong>Sketch <\/strong>> <strong>Include Library<\/strong> > <strong>Add . ZIP library<\/strong>&#8230;<\/li>\n\n\n\n<li>Select the .ZIP file of the library you just downloaded.<\/li>\n\n\n\n<li>The library will be installed after a few seconds.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Getting Date and Time from NTP Server<\/h2>\n\n\n\n<p>Here we provide a sample code to get date and time from the NTP Server. This example was modified from one of the library examples.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">\/*********\n  Rui Santos\n  Complete project details at https:\/\/randomnerdtutorials.com\n  Based on the NTP Client library example\n*********\/\n\n#include &lt;WiFi.h&gt;\n#include &lt;NTPClient.h&gt;\n#include &lt;WiFiUdp.h&gt;\n\n\/\/ Replace with your network credentials\nconst char* ssid     = &quot;REPLACE_WITH_YOUR_SSID&quot;;\nconst char* password = &quot;REPLACE_WITH_YOUR_PASSWORD&quot;;\n\n\/\/ Define NTP Client to get time\nWiFiUDP ntpUDP;\nNTPClient timeClient(ntpUDP);\n\n\/\/ Variables to save date and time\nString formattedDate;\nString dayStamp;\nString timeStamp;\n\nvoid setup() {\n  \/\/ Initialize Serial Monitor\n  Serial.begin(115200);\n  Serial.print(&quot;Connecting to &quot;);\n  Serial.println(ssid);\n  WiFi.begin(ssid, password);\n  while (WiFi.status() != WL_CONNECTED) {\n    delay(500);\n    Serial.print(&quot;.&quot;);\n  }\n  \/\/ Print local IP address and start web server\n  Serial.println(&quot;&quot;);\n  Serial.println(&quot;WiFi connected.&quot;);\n  Serial.println(&quot;IP address: &quot;);\n  Serial.println(WiFi.localIP());\n\n\/\/ Initialize a NTPClient to get time\n  timeClient.begin();\n  \/\/ Set offset time in seconds to adjust for your timezone, for example:\n  \/\/ GMT +1 = 3600\n  \/\/ GMT +8 = 28800\n  \/\/ GMT -1 = -3600\n  \/\/ GMT 0 = 0\n  timeClient.setTimeOffset(3600);\n}\nvoid loop() {\n  while(!timeClient.update()) {\n    timeClient.forceUpdate();\n  }\n  \/\/ The formattedDate comes with the following format:\n  \/\/ 2018-05-28T16:00:13Z\n  \/\/ We need to extract date and time\n  formattedDate = timeClient.getFormattedDate();\n  Serial.println(formattedDate);\n\n  \/\/ Extract date\n  int splitT = formattedDate.indexOf(&quot;T&quot;);\n  dayStamp = formattedDate.substring(0, splitT);\n  Serial.print(&quot;DATE: &quot;);\n  Serial.println(dayStamp);\n  \/\/ Extract time\n  timeStamp = formattedDate.substring(splitT+1, formattedDate.length()-1);\n  Serial.print(&quot;HOUR: &quot;);\n  Serial.println(timeStamp);\n  delay(1000);\n}\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/ESP32\/ESP32_NTPClient.ino\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>To get more NTP examples, in the Arduino IDE, go to <strong>File&nbsp;<\/strong>&gt;&nbsp;<strong>Examples&nbsp;<\/strong>&gt;&nbsp;<strong>NTPClient<\/strong>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How the Code Works<\/h2>\n\n\n\n<p>Let\u2019s take a quick look at the code to see how it works. First, you include the libraries to connect to Wi-Fi and get time and create an NTP client.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#include &lt;WiFi.h&gt;\n#include &lt;NTPClient.h&gt;\n#include &lt;WiFiUdp.h&gt;<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Setting SSID and password<\/h3>\n\n\n\n<p>Type your network credentials in the following variables, so that the ESP32 is able to establish an Internet connection and get date and time from the NTP server.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Replace with your network credentials\nconst char* ssid = \"REPLACE_WITH_YOUR_SSID\";\nconst char* password = \"REPLACE_WITH_YOUR_PASSWORD\";<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Preparing NTP Client<\/h3>\n\n\n\n<p>The following two lines define an NTP Client to request date and time from an NTP server.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>WiFiUDP ntpUDP;\nNTPClient timeClient(ntpUDP);<\/code><\/pre>\n\n\n\n<p>Then, initialize <em>String<\/em> variables to save the date and time.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>String formattedDate;\nString dayStamp;\nString timeStamp;<\/code><\/pre>\n\n\n\n<p>In the <span class=\"rnthl rntliteral\">setup()<\/span> you initialize the Serial communication at baud rate 115200 to print the results:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>Serial.begin(115200);<\/code><\/pre>\n\n\n\n<p>These next lines connect the ESP32 to your router.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Initialize Serial Monitor\nSerial.begin(115200);\nSerial.print(\"Connecting to \");\nSerial.println(ssid);\nWiFi.begin(ssid, password);\nwhile (WiFi.status() != WL_CONNECTED) {\n  delay(500);\n  Serial.print(\".\");\n}\n\/\/ Print local IP address and start web server\nSerial.println(\"\");\nSerial.println(\"WiFi connected.\");\nSerial.println(\"IP address: \");\nSerial.println(WiFi.localIP());<\/code><\/pre>\n\n\n\n<p>Next, initialize the NTP client to get date and time from an NTP server.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>timeClient.begin();<\/code><\/pre>\n\n\n\n<p>You can use the <span class=\"rnthl rntliteral\">setTimeOffset()<\/span> method to adjust the time for your timezone in seconds.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>timeClient.setTimeOffset(3600);<\/code><\/pre>\n\n\n\n<p>Here are some examples for different timezones:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>GMT +1 = 3600<\/li>\n\n\n\n<li>GMT +8 = 28800<\/li>\n\n\n\n<li>GMT -1 = -3600<\/li>\n\n\n\n<li>GMT 0 = 0<\/li>\n<\/ul>\n\n\n\n<p>These next lines ensure that we get a valid date and time:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>while(!timeClient.update()) {\n  timeClient.forceUpdate();\n}<\/code><\/pre>\n\n\n\n<p><strong>Note:<\/strong> sometimes the NTP Client retrieves 1970. To ensure that doesn\u2019t happen we need to force the update.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Getting date and time<\/h3>\n\n\n\n<p>Then, convert the date and time to a readable format with the <span class=\"rnthl rntliteral\">getFormattedDate()<\/span> method:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>formattedDate = timeClient.getFormattedDate();<\/code><\/pre>\n\n\n\n<p>The date and time are returned in the following format:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">2018-04-30<strong>T<\/strong>16:00:13<strong>Z<\/strong><\/pre>\n\n\n\n<p>If you want to get date and time separately, you need to split that string. The &#8220;T&#8221; letter separates the date from the time, so we can easily split that String. That\u2019s what we do in these next lines.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Extract date\nint splitT = formattedDate.indexOf(\"T\");\ndayStamp = formattedDate.substring(0, splitT);\nSerial.println(dayStamp);\n\/\/ Extract time\ntimeStamp = formattedDate.substring(splitT+1, formattedDate.length()-1);\nSerial.println(timeStamp);<\/code><\/pre>\n\n\n\n<p>The date is saved on the <span class=\"rnthl rntliteral\">dayStamp<\/span> variable, and the time on the <span class=\"rnthl rntliteral\">timeStamp<\/span> variable.The time is requested and printed in every second.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Testing the Code<\/h2>\n\n\n\n<p>Upload the code to the ESP32. Make sure you have the right board and COM port selected. After uploading the code, press the ESP32 &#8220;Enable&#8221; button, and you should get the date and time every second as shown in the following figure.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"753\" height=\"443\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/06\/date_and_time_ESP32.png?resize=753%2C443&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-66812\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/06\/date_and_time_ESP32.png?w=753&amp;quality=100&amp;strip=all&amp;ssl=1 753w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/06\/date_and_time_ESP32.png?resize=300%2C176&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 753px) 100vw, 753px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>In this tutorial we\u2019ve shown you how to easily get date and time with the ESP32 on the Arduino IDE using an NTP server. The code provided is not useful by itself. The idea is to use the example provided in this guide in your own projects to timestamp your sensor readings.<\/p>\n\n\n\n<p>This method only works if the ESP32 is connected to the Internet. If your project doesn\u2019t have access to the internet, you need to use other method. You can use an <a href=\"https:\/\/makeradvisor.com\/tools\/real-time-clock-module-ds1307\/\" target=\"_blank\" rel=\"noreferrer noopener\">RTC module like the DS1307<\/a>.<\/p>\n\n\n\n<p>We have other tutorials related with ESP32 that you may also like:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/learn-esp32-with-arduino-ide\/\">Learn ESP32 with Arduino IDE Course<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-data-logging-temperature-to-microsd-card\/\">ESP32 Data Logging Temperature to MicroSD Card<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-esp8266-publish-sensor-readings-to-google-sheets\/\">ESP32 Publish Sensor Readings to Google Sheets<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/build-an-all-in-one-esp32-weather-station-shield\/\">Build an All-in-One ESP32 Weather Station Shield<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-bluetooth-low-energy-ble-arduino-ide\/\">Getting Started with ESP32 Bluetooth Low Energy (BLE)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-lora-rfm95-transceiver-arduino-ide\/\">ESP32 with LoRa using Arduino IDE<\/a><\/li>\n<\/ul>\n\n\n\n<p>Thanks for reading.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial we\u2019ll show you how to get date and time using the ESP32 and Arduino IDE. Getting date and time is especially useful in data logging to timestamp &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Getting Date and Time with ESP32 on Arduino IDE (NTP Client)\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/esp32-ntp-client-date-time-arduino-ide\/#more-66810\" aria-label=\"Read more about Getting Date and Time with ESP32 on Arduino IDE (NTP Client)\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":67887,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[276,281,277,299,264],"tags":[],"class_list":["post-66810","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-esp32","category-esp32-project","category-esp32-arduino-ide","category-0-esp32","category-project"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/07\/NTPClient-ESP32-featured.jpg?fit=1280%2C720&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/66810","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/comments?post=66810"}],"version-history":[{"count":3,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/66810\/revisions"}],"predecessor-version":[{"id":158844,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/66810\/revisions\/158844"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/67887"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=66810"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=66810"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=66810"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}