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

Added two new methods to return Date and Time as a struct and get formatted Date Time string with a given format #94

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions NTPClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,23 @@ int NTPClient::getSeconds() const {
return (this->getEpochTime() % 60);
}

DateTime NTPClient::getDateTime() const {
struct tm * ts;
time_t rawTime = this->getEpochTime();
ts = localtime(&rawTime);
DateTime dt = {ts->tm_sec, ts->tm_min, ts->tm_hour, ts->tm_mday, (ts->tm_mon + 1), (ts->tm_year + 1900)};
return dt;
}

String NTPClient::formatDateTime(const char* fmt) const {
per1234 marked this conversation as resolved.
Show resolved Hide resolved
struct tm * ts;
time_t rawTime = this->getEpochTime();
ts = localtime(&rawTime);
char buf[64];
strftime(buf, sizeof(buf), fmt, ts);
return String(buf);
}

String NTPClient::getFormattedTime() const {
unsigned long rawTime = this->getEpochTime();
unsigned long hours = (rawTime % 86400L) / 3600;
Expand Down
21 changes: 21 additions & 0 deletions NTPClient.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,21 @@
#include "Arduino.h"

#include <Udp.h>
#include <time.h>

#define SEVENZYYEARS 2208988800UL
#define NTP_PACKET_SIZE 48
#define NTP_DEFAULT_LOCAL_PORT 1337

struct DateTime {
int dt_seconds;
int dt_minutes;
int dt_hours;
int dt_date;
int dt_month;
int dt_year;
};

class NTPClient {
private:
UDP* _udp;
Expand Down Expand Up @@ -74,6 +84,17 @@ class NTPClient {
int getMinutes() const;
int getSeconds() const;

/**
* Get date time as a astuct which contains
per1234 marked this conversation as resolved.
Show resolved Hide resolved
* Year, Month, Date, Hours, Minutes, Seconds
*/
DateTime getDateTime() const;

/**
* Format the date time to a string with a given format (Ex: %Y/%m/%d %H:%M:%S)
per1234 marked this conversation as resolved.
Show resolved Hide resolved
*/
String formatDateTime(const char* fmt) const;
per1234 marked this conversation as resolved.
Show resolved Hide resolved

/**
* Changes the time offset. Useful for changing timezones dynamically
*/
Expand Down