ESP32 NTP Time - Setting Up Timezones and Daylight Saving Time | Random Nerd Tutorials (2024)

In this tutorial, you’ll learn how to properly get the time with the ESP32 for your timezone and consider daylight saving time (if that’s the case). The ESP32 will request the time from an NTP server, and the time will be automatically adjusted for your timezone with or without daylight saving time.

ESP32 NTP Time - Setting Up Timezones and Daylight Saving Time | Random Nerd Tutorials (1)

Quick Answer: call setenv(“TZ”, timezone, 1), where timezone is one of the timezones listed here. Then, call tzset() to update to that timezone.

If you’re getting started, we recommend taking a look at the following tutorial first to learn how to get date and time from an NTP server:

  • ESP32 NTP Client-Server: Get Date and Time (Arduino IDE)

In that previous tutorial, we’ve shown an option to set up your timezone. However, that example doesn’t take into account daylight saving time. Continue reading this tutorial to learn how to set up the timezone and daylight saving time properly.

Thanks to one of our readers (Hardy Maxa) who shared this information with us.

ESP32 Setting Timezone with Daylight Saving Time

According to documentation:

“To set local timezone, use setenv and tzset POSIX functions. First, call setenv to set TZ environment variable to the correct value depending on device location. Format of the time string is described in libc documentation. Next, call tzset to update C library runtime data for the new time zone. Once these steps are done, localtime function will return correct local time, taking time zone offset and daylight saving time into account.”

You can check a list of timezone string variables here.

For example, I live in Porto. The timezone is Europe/Lisbon. From the list of timezone string variables, I see that the timezone string variable for my location is WET0WEST,M3.5.0/1,M10.5.0, so after connecting to the NTP server, to get the time for my location I need to call:

setenv("TZ","WET0WEST,M3.5.0/1,M10.5.0",1);

Followed by:

tzset();

Let’s look at a demo sketch to understand how it works and how to use it in your ESP32 project.

ESP32 Timezone and DST Example Sketch

The following example was provided by one of our followers (Hardy Maxa), we’ve just made a few modifications.

Copy the following code to your Arduino IDE.

// RTC demo for ESP32, that includes TZ and DST adjustments// Get the POSIX style TZ format string from https://github.com/nayarsystems/posix_tz_db/blob/master/zones.csv// Created by Hardy Maxa// Complete project details at: https://RandomNerdTutorials.com/esp32-ntp-timezones-daylight-saving/#include <WiFi.h>#include "time.h"const char * ssid="REPLACE_WITH_YOUR_SSID";const char * wifipw="REPLACE_WITH_YOUR_PASSWORD";void setTimezone(String timezone){ Serial.printf(" Setting Timezone to %s\n",timezone.c_str()); setenv("TZ",timezone.c_str(),1); // Now adjust the TZ. Clock settings are adjusted to show the new local time tzset();}void initTime(String timezone){ struct tm timeinfo; Serial.println("Setting up time"); configTime(0, 0, "pool.ntp.org"); // First connect to NTP server, with 0 TZ offset if(!getLocalTime(&timeinfo)){ Serial.println(" Failed to obtain time"); return; } Serial.println(" Got the time from NTP"); // Now we can set the real timezone setTimezone(timezone);}void printLocalTime(){ struct tm timeinfo; if(!getLocalTime(&timeinfo)){ Serial.println("Failed to obtain time 1"); return; } Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S zone %Z %z ");}void startWifi(){ WiFi.begin(ssid, wifipw); Serial.println("Connecting Wifi"); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.print("Wifi RSSI="); Serial.println(WiFi.RSSI());}void setTime(int yr, int month, int mday, int hr, int minute, int sec, int isDst){ struct tm tm; tm.tm_year = yr - 1900; // Set date tm.tm_mon = month-1; tm.tm_mday = mday; tm.tm_hour = hr; // Set time tm.tm_min = minute; tm.tm_sec = sec; tm.tm_isdst = isDst; // 1 or 0 time_t t = mktime(&tm); Serial.printf("Setting time: %s", asctime(&tm)); struct timeval now = { .tv_sec = t }; settimeofday(&now, NULL);}void setup(){ Serial.begin(115200); Serial.setDebugOutput(true); startWifi(); initTime("WET0WEST,M3.5.0/1,M10.5.0"); // Set for Melbourne/AU printLocalTime();}void loop() { int i; // put your main code here, to run repeatedly: Serial.println("Lets show the time for a bit. Starting with TZ set for Melbourne/Australia"); for(i=0; i<10; i++){ delay(1000); printLocalTime(); } Serial.println(); Serial.println("Now - change timezones to Berlin"); setTimezone("CET-1CEST,M3.5.0,M10.5.0/3"); for(i=0; i<10; i++){ delay(1000); printLocalTime(); } Serial.println(); Serial.println("Now - Lets change back to Lisbon and watch Daylight savings take effect"); setTimezone("WET0WEST,M3.5.0/1,M10.5.0"); printLocalTime(); Serial.println(); Serial.println("Now change the time. 1 min before DST takes effect. (1st Sunday of Oct)"); Serial.println("AEST = Australian Eastern Standard Time. = UTC+10"); Serial.println("AEDT = Australian Eastern Daylight Time. = UTC+11"); setTime(2021,10,31,0,59,50,0); // Set it to 1 minute before daylight savings comes in. for(i=0; i<20; i++){ delay(1000); printLocalTime(); } Serial.println("Now change the time. 1 min before DST should finish. (1st Sunday of April)"); setTime(2021,3,28,1,59,50,1); // Set it to 1 minute before daylight savings comes in. Note. isDst=1 to indicate that the time we set is in DST. for(i=0; i<20; i++){ delay(1000); printLocalTime(); } // Now lets watch the time and see how long it takes for NTP to fix the clock Serial.println("Waiting for NTP update (expect in about 1 hour)"); while(1) { delay(1000); printLocalTime(); }}

View raw code

How the Code Works

First, you need to include the WiFi library to connect the ESP32 to the internet (NTP server) and the time library to deal with time.

#include <WiFi.h>#include "time.h"

To set the timezone, we created a function called setTimezone() that accepts as an argument a timezone string.

void setTimezone(String timezone){

Inside that function, we call the setenv() function for the TZ (timezone) parameter to set the timezone with whatever timezone you pass as an argument to the setTimezone() function.

setenv("TZ",timezone.c_str(),1); // Now adjust the TZ. Clock settings are adjusted to show the new local time

After that, call the tzset() function for the changes to take effect.

tzset();

We won’t go into detail about the other functions declared in the code because those were already explained in a previous tutorial:

  • ESP32 NTP Client-Server: Get Date and Time (Arduino IDE)

setup()

In the setup(), we initialize Wi-Fi so that the ESP32 can connect to the internet to connect to the NTP server.

initWifi();

Then, call the initTime() function and pass as argument the timezone String. In our case, for Lisbon/PT timezone.

initTime("WET0WEST,M3.5.0/1,M10.5.0"); // Set for Lisbon/PT

After that, print the current local time.

printLocalTime();

loop()

In the loop() show the local time for ten seconds.

Serial.println("Lets show the time for a bit. Starting with TZ set for Lisbon/Portugal");for(i=0; i<10; i++){ delay(1000); printLocalTime();}

If at any time in your code you need to change the timezone, you can do it by calling the setTimezone() function and passing as an argument the timezone string. For example, the following lines change the timezone to Berlin and display the time for ten seconds.

Serial.println();Serial.println("Now - change timezones to Berlin");setTimezone("CET-1CEST,M3.5.0,M10.5.0/3");for(i=0; i<10; i++){ delay(1000); printLocalTime();}

Then, we go back to our local time by calling the setTimezone() function again with the Lisbon/PT timezone string variable.

Serial.println();Serial.println("Now - Lets change back to Lisbon and watch Daylight savings take effect");setTimezone("WET0WEST,M3.5.0/1,M10.5.0");printLocalTime();

To check if daylight saving time is taking effect, we’ll change the time to 10 seconds before the winter time takes effect. In our case, it is on the last Sunday of October (it might be different for your location).

Serial.println();Serial.println("Now change the time. 1 min before DST takes effect. (Last Sunday of Oct)");setTime(2021,10,31,0,59,50,0); // Set it to 1 minute before daylight savings comes in.

Then, show the time for a while to check that it is adjusting the time, taking into account DST.

for(i=0; i<20; i++){ delay(1000); printLocalTime();}

After this, let’s change the time again to check if it changes to summer time when it comes the time. In our case, it is on the last Sunday of March.

Serial.println("Now change the time. 1 min before DST should finish. (Last Sunday of March)");setTime(2021,3,28,1,59,50,1); // Set it to 1 minute before daylight savings comes in. Note. isDst=1 to indicate that the time we set is in DST.

Show the time for a while to check that it is adjusting to the summer time.

for(i=0; i<20; i++){ delay(1000); printLocalTime();}

Demonstration

Now, let’s test the code. After inserting your network credentials, upload the code to your ESP32.

After that, open the Serial Monitor at a baud rate of 115200 and press the ESP32 RST button to start running the code.

First, it shows your local time with the timezone you’ve set on the code.

ESP32 NTP Time - Setting Up Timezones and Daylight Saving Time | Random Nerd Tutorials (2)

After that, it will change to the other timezone you’ve set on the code. In our case, we set to Berlin.

ESP32 NTP Time - Setting Up Timezones and Daylight Saving Time | Random Nerd Tutorials (3)

After that, you should see the change to winter time. In our case, when it’s 2 a.m., the clock goes back one hour.

ESP32 NTP Time - Setting Up Timezones and Daylight Saving Time | Random Nerd Tutorials (4)

We also check if it adjusts to summer time when it comes the time. In the example below, you can see that the clock goes forward one hour to set summer time.

ESP32 NTP Time - Setting Up Timezones and Daylight Saving Time | Random Nerd Tutorials (5)

Wrapping Up

This quick tutorial taught you how to set timezone with daylight saving time using the setenv() and tzset() functions.

We hope you found this tutorial useful. We have other tutorials related to time that you may like:

  • ESP32 NTP Client-Server: Get Date and Time (Arduino IDE)
  • Getting Date and Time with ESP32 on Arduino IDE (NTP Client)
  • ESP32 Data Logging Temperature to MicroSD Card (with NTP time)

Learn more about the ESP32 with our resources:

  • Build Web Servers with ESP32 and ESP8266 eBook
  • Learn ESP32 with Arduino IDE (eBook + video course)
  • More ESP32 tutorials and projects

Thank you for reading.

ESP32 NTP Time - Setting Up Timezones and Daylight Saving Time | Random Nerd Tutorials (2024)

FAQs

How do I set NTP time on ESP32? ›

To set the current time, you can use the POSIX functions settimeofday() and adjtime() . They are used internally in the lwIP SNTP library to set current time when a response from the NTP server is received. These functions can also be used separately from the lwIP SNTP library.

How does NTP handle daylight savings time? ›

Because NTP is based on UTC which does not have a daylight savings time period, a switchover is not necessary inside the NTP system. The operation systems of servers and clients are solely responsible for switching from/to DST.

Can NTP set timezone? ›

NTP does not regconize time zones, instead it manages all time informations based on UTC. In general the handling of time zones is a job of a computer's operating system.

How to set NTP configuration? ›

Start the Local Windows NTP Time Service
  1. In the File Explorer, navigate to: Control Panel\System and Security\Administrative Tools.
  2. Double-click Services.
  3. In the Services list, right-click on Windows Time and configure the following settings: Startup type: Automatic. Service Status: Start. OK.

How do I manually set up NTP server? ›

To set an NTP server
  1. To set an NTP server. In an elevated command prompt type: w32tm /config /manualpeerlist:us.pool.ntp.org. ...
  2. You now need to restart the windows time service for your change to take effect. ...
  3. That's the basics of how to change your time server from one source to another.

How does daylight savings change time zones? ›

The nighttime light exposures delay the body clock in relation to the sun clock (Roenneberg et al., 2003a), which translates to living further west is a time zone, while DST advances the social clock in relation to the sun clock, which translates into moving the time zone further east.

What is NTP and DST? ›

Sometime the device date/time may be incorrect. In order to avoid this, HIKVISION devices use NTP (Network Time Protocol) as well as DST (Daylight Saving Time) to adjust device time.

How to synchronize time using NTP? ›

Set the start mode of ntpd and the server to query on the General Settings tab. Select Only Manually, if you want to manually start the ntpd daemon. Select Synchronize without Daemon to set the system time periodically without a permanently running ntpd . You can set the Interval of the Synchronization in Minutes.

Is NTP always UTC? ›

NTP servers operate always in UTC, so local time change cannot affect their operation. However, you may want to ensure that the device you are using is correctly up to date concerning time zone information.

What is more accurate than NTP? ›

For that reason alone, PTP networks have much sharper time resolutions, and unlike NTP, PTP devices will actually timestamp the amount of time that synchronization messages spend in each device, which accounts for device latency.

What is the default time zone for NTP? ›

NTP uses Coordinated Universal Time (UTC) as the universal standard for current time.

Does the ESP32 have a real-time clock? ›

The ESP32 RTC module only has a timer that runs even in hibernation mode as well as some RAM that it can retain in deep sleep mode. There are some interrupt inputs that can be used to have the RTC wake up the main processor. There's no "wall clock" or "calendar" in the ESP32 RTC module.

How do I get local timezone ESP32? ›

“To set local timezone, use setenv and tzset POSIX functions. First, call setenv to set TZ environment variable to the correct value depending on device location. Format of the time string is described in libc documentation. Next, call tzset to update C library runtime data for the new time zone.

How do I set NTP time sync? ›

To enable time synchronization with an NTP server, do the following:
  1. In the Use NTP to set clock window, click Yes. ...
  2. In the Configure NTP servers window, select New. ...
  3. In the NTP server field, enter the IP address or URL of the NTP, which you want to set the time synchronization with.
  4. Click Ok. ...
  5. Select Continue.

How to use timer in ESP32? ›

The function timerBegin(uint8_t id, uint16_t prescaler, bool countUp) allows to configure the timer : The ESP32 has 4 independent timers, selected by an id between 0 and 3. Then we select the prescaler to apply to the timer clock signal. On the ESP32, this is the APB_CLK clock, clocked at 80 MHz.

How do I keep time on ESP32? ›

ESP32 uses two hardware timers for the purpose of keeping system time. System time can be kept by using either one or both of the hardware timers depending on the application's purpose and accuracy requirements for system time.

How do I change time source to NTP? ›

To do this, follow these steps: Select Start > Run, type regedit, and then select OK. In the pane on the right, right-click Type, and then select Modify. In Edit Value, type NTP in the Value data box, and then select OK.

Top Articles
Latest Posts
Article information

Author: Trent Wehner

Last Updated:

Views: 5868

Rating: 4.6 / 5 (56 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Trent Wehner

Birthday: 1993-03-14

Address: 872 Kevin Squares, New Codyville, AK 01785-0416

Phone: +18698800304764

Job: Senior Farming Developer

Hobby: Paintball, Calligraphy, Hunting, Flying disc, Lapidary, Rafting, Inline skating

Introduction: My name is Trent Wehner, I am a talented, brainy, zealous, light, funny, gleaming, attractive person who loves writing and wants to share my knowledge and understanding with you.