NTPClient cannot calculate time next 5 Minute

I get time by using NTPClient. I want to calculate time next 5 min from current time. So, I use formattedTime + (5*60) like this code.

 #include <ESP8266WiFi.h>
 #include <NTPClient.h>
 #include <WiFiUdp.h>
 
 // Replace with your network credentials
 const char *ssid     = "ssidWiFi";
 const char *password = "pass";
 
 // Define NTP Client to get time
 WiFiUDP ntpUDP;
 NTPClient timeClient(ntpUDP, "pool.ntp.org");
 
 
 void setup() {
   // Initialize Serial Monitor
   Serial.begin(115200);
   
   // Connect to Wi-Fi
   Serial.print("Connecting to ");
   Serial.println(ssid);
   WiFi.begin(ssid, password);
   while (WiFi.status() != WL_CONNECTED) {
     delay(500);
     Serial.print(".");
   }
 
 // Initialize a NTPClient to get time
   timeClient.begin();
   const long offsetTime = 25200;
   timeClient.setTimeOffset(offsetTime);
 }
 
 void loop() {
   timeClient.update();
 
   
   String formattedTime = timeClient.getFormattedTime();
   Serial.print("Formatted Time: ");
   Serial.println(formattedTime);  
 
   Serial.print("Next 5 min: ");
   Serial.println(formattedTime + (5*60));      // Calculate next 5 min

   Serial.println("");
 
   delay(2000);
 }

The output show like this.

Formatted Time: 14:59:25
Next 5 min: 14:59:25300

็How to calculate time next 5 minute by using NTPClient ?

As you have discovered you cannot just add a period in seconds to the formatted date/time

You would be better off using the Unix epoch time, which is the number of seconds that have elapsed since January 1, 1970, to do the calculation

See Get Epoch/Unix Time with the ESP32 (Arduino) | Random Nerd Tutorials for how to get the value

Your machine multiplied 5 by 60 to get 300, and then attached that 300 to the end of your time String "14:59:25" to get the result "14:59:25300".
That's what happens if you try adding a number to a String. (Really, what did you expect to happen?)

I'm probably going to get some virtual tomatoes thrown at me for posting this, but here goes:

   String formattedTime = timeClient.getFormattedTime();
   Serial.print("Formatted Time: ");
   Serial.println(formattedTime);  
   
   // create a string to hold the new time
   String newTime;
   // copy the old formatted time into the new time
   newTime = formattedTime;
   // make sure our string is long enough
   //  01234567
   // "HH:MM:SS"
   if ((newTime.length())>=8) {
     // advance the time 5 minutes
     newTime[4] += 5;
     // do carries
     if (newTime[4] > '9') { newTime[4] -= 10; newTime[3]++; }
     if (newTime[3] > '5') { newTime[3] -=  6; newTime[1]++; }
     if (newTime[1] > '9') { newTime[1] -= 10; newTime[0]++; }
     if ((newTime[0] >= '2') && (newTime[1] >= '4')) {
       newTime[0] -= 2; newTime[1] -= 4;
     }
     else if (newTime[0] >= '3') {
       newTime[0] -= 3; newTime[1] += 6;
     }
   }
   
   // now we have the new time, so let's print it
   Serial.print("Next 5 min: ");
   Serial.println(newTime);      // Calculate next 5 min

Using the Unix epoch time makes it trivial to add 5 minute, or any other period, to the current time

#include <WiFi.h>
#include <WiFiUdp.h>
#include <NTPClient.h>        // include NTPClient library
#include <TimeLib.h>          // Include Arduino time library
#include <Adafruit_GFX.h>     // include Adafruit graphics library
#include "credentials.h"

WiFiUDP ntpUDP;

// 'time.nist.gov' is used (default server) with +1 hour offset (3600 seconds) 60 seconds (60000 milliseconds) update interval
NTPClient timeClient(ntpUDP, "time.nist.gov", 3600, 60000);
unsigned long unix_epoch;

void setup(void)
{
  Serial.begin(115200);
  WiFi.begin(mySSID, myPASSWORD);
  Serial.print("\nConnecting.");
  while ( WiFi.status() != WL_CONNECTED )
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("connected");
  timeClient.begin();
}

void RTC_display()
{
  Serial.printf( "current\t\t\t%02u-%02u-%04u ", day(unix_epoch), month(unix_epoch), year(unix_epoch) );
  Serial.printf( "%02u:%02u:%02u\n", hour(unix_epoch), minute(unix_epoch), second(unix_epoch) );
  unsigned long unix_epochPlus5 = unix_epoch + 60 * 5;
  Serial.printf( "current + 5 mins\t%02u-%02u-%04u ", day(unix_epochPlus5), month(unix_epochPlus5), year(unix_epochPlus5) );
  Serial.printf( "%02u:%02u:%02u\n\n", hour(unix_epochPlus5), minute(unix_epochPlus5), second(unix_epoch) );
}

void loop()
{
  timeClient.update();
  unix_epoch = timeClient.getEpochTime();   // get UNIX Epoch time
  RTC_display();
  delay(1000);
}

This example shows how to add a period to the current time. The addition could, of course, be done at any time and later compared to the actual time at that point

In addition to all info already provided, external libraries to handle NTP time are completely useless with ESP8266. There is everything you need already included in the Arduino core.

1 Like

Useless how ?

Did you perhaps mean unnecessary ?

Feel free to revise my example to illustrate what you mean

Sorry for my bad English, however there is already this very good example included in the core which can be minimized this way:

#include <ESP8266WiFi.h>

// Timezone and DST definition
#include <time.h>
#define MYTZ "CET-1CEST,M3.5.0,M10.5.0/3"

const char* ssid     = "xxxxxxxxx";
const char* password = "xxxxxxxxxxxx";

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  
  configTime(MYTZ, "time.google.com", "time.windows.com", "pool.ntp.org"); 
  // A small delay in order to get NTP synced
  delay(3000);
}

void showTime() {
  static int32_t updateTime;
  if (millis() - updateTime > 1000) {
    updateTime = millis();
    
    struct tm tInfo;    // defined in "time.h"
    time_t epoch = time(nullptr); 

    // Add 5 minutes
    epoch += 60*5;
   
    // Get tm struct starting from epoch time
    tInfo= *localtime(&epoch );
  
    // https://www.cplusplus.com/reference/ctime/strftime/
    char buffer [40];
    strftime (buffer,40,"%A, %D %T", &tInfo);
    Serial.println(buffer);
    
    /* Alternative way
     Serial.printf("%02d/%02d/%04d - %02d:%02d:%02d\n", 
                tInfo.tm_mday, tInfo.tm_mon + 1, tInfo.tm_year + 1900,
                tInfo.tm_hour, tInfo.tm_min, tInfo.tm_sec);
    */

  }
}

void loop() {
  showTime();
}

No problem, especially as my Italian is non existent :grinning:

I just wanted to clarify exactly what you meant so thanks for posting the example

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.