arduino-libraries / NTPClient

Connect to a NTP server
554 stars 376 forks source link

Add the functionallity to get the date #190

Open Neoxxgr opened 1 year ago

Neoxxgr commented 1 year ago

With the code below you can add the function to get the date from the rawTime this is a test code and i have not tested it very well NTPClient.h

/**
 * @return Date formatted like `dd/mm/yyyy`
*/
String getFormattedDate() const;

NTPClient.cpp

String NTPClient::getFormattedDate() const {
   unsigned long rawTime = this->getEpochTime();
  // Define constants for seconds in a day, year, and leap year
  #define SEC_IN_DAY 86400
  #define SEC_IN_YEAR 31536000
  #define SEC_IN_LEAP_YEAR 31622400

  // Define an array for the number of days in each month
  int days_in_month[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

  // Initialize the date to January 1st, 1970
  unsigned long years = 1970;
  unsigned long months = 1;
  unsigned long days = 1;

  // Add the number of years elapsed since the epoch
  while (rawTime >= SEC_IN_YEAR) 
  {
    if ((years % 4 == 0 && years % 100 != 0) || (years % 400 == 0)) 
    {
      if (rawTime >= SEC_IN_LEAP_YEAR) 
      {
        rawTime -= SEC_IN_LEAP_YEAR;
        years++;
      } else 
      {
        break; // not enough seconds for a leap year
      }
    } else 
    {
      rawTime -= SEC_IN_YEAR;
      years++;
    }
  }

  // Add the number of months elapsed in the current year
  while (rawTime >= SEC_IN_DAY) 
  {
    if (rawTime >= days_in_month[months - 1] * SEC_IN_DAY) 
    {
      rawTime -= days_in_month[months - 1] * SEC_IN_DAY;
      months++;
    } else 
    {
      break; // not enough seconds for a month
    }
    // Adjust for February in a leap year
    if (months == 2 && ((years % 4 == 0 && years % 100 != 0) || (years % 400 == 0))) 
    {
      rawTime -= SEC_IN_DAY;
    }  

    // Adjust for year boundary
    if (months >12) {
      months = months -12;
      years++;
    }
  }

    // Add the number of days elapsed in the current month 
    while (rawTime >= SEC_IN_DAY) { rawTime -= SEC_IN_DAY; days++; }

    // Convert the date components to strings with leading zeros if needed  
    String yearStr = String(years);
    String monthStr = months <10 ? "0" + String(months) : String(months);
    String dayStr = days <10 ? "0" + String(days) : String(days);

    // Return the date in dd/mm/yyyy format 
    return dayStr + "/" + monthStr + "/" + yearStr; 
    }
per1234 commented 1 year ago

Thanks for your suggestion @Neoxxgr. In order to make it easy for the interested parties to find all the relevant information, I'll share the links to related proposals: