Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hey!! It will be great if you can add date and month functions as well. #29

Open
shariramani opened this issue Apr 13, 2017 · 1 comment
Labels
topic: code Related to content of the project itself type: enhancement Proposed improvement

Comments

@shariramani
Copy link

Please add date and month function. May be you can add something like
13 April 1974, Wednesday

@sheffieldnikki
Copy link
Contributor

sheffieldnikki commented Apr 24, 2017

I've just written a getFormattedDate() method for my own use, that outputs an ISO 8601 date/time string. Here it is, in case anyone finds it useful.

Aside: there is a line to draw between having a lean, minimal library with limited functionality, and adding so many features that you have a bloated mess that would be better provided by using separate libraries... but where to draw it?

NTPClient.h:

/**
 * @return secs argument (or 0 for current date) formatted to ISO 8601
 * like `2004-02-12T15:19:21+00:00`
 */
String getFormattedDate(unsigned long secs = 0);

NTPClient.cpp:

#define LEAP_YEAR(Y)     ( (Y>0) && !(Y%4) && ( (Y%100) || !(Y%400) ) )

// Based on https://github.com/PaulStoffregen/Time/blob/master/Time.cpp
// currently assumes UTC timezone, instead of using this->_timeOffset
String NTPClient::getFormattedDate(unsigned long secs) {
  unsigned long rawTime = (secs ? secs : this->getEpochTime()) / 86400L;  // in days
  unsigned long days = 0, year = 1970;
  uint8_t month;
  static const uint8_t monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31};

  while((days += (LEAP_YEAR(year) ? 366 : 365)) <= rawTime)
    year++;
  rawTime -= days - (LEAP_YEAR(year) ? 366 : 365); // now it is days in this year, starting at 0
  days=0;
  for (month=0; month<12; month++) {
    uint8_t monthLength;
    if (month==1) { // february
      monthLength = LEAP_YEAR(year) ? 29 : 28;
    } else {
      monthLength = monthDays[month];
    }
    if (rawTime < monthLength) break;
    rawTime -= monthLength;
  }
  String monthStr = ++month < 10 ? "0" + String(month) : String(month); // jan is month 1  
  String dayStr = ++rawTime < 10 ? "0" + String(rawTime) : String(rawTime); // day of month  
  return String(year) + "-" + monthStr + "-" + dayStr + "T" + this->getFormattedTime(secs ? secs : 0) + "Z";
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
topic: code Related to content of the project itself type: enhancement Proposed improvement
Projects
None yet
Development

No branches or pull requests

3 participants