添加新函数
timeClient.getYear();//获取年
timeClient.getMonth();//获取月
timeClient.getDate();//获取日
在NtpClient.h中添加
int getYear();
int getMonth();
int getDate();
在NtpClient.cpp中添加
// 获取年份
int NTPClient::getYear()
{
time_t rawtime = this->getEpochTime();
struct tm *ti;
ti = localtime(&rawtime);
int year = ti->tm_year + 1900;
return year;
}
// 获取月份
int NTPClient::getMonth()
{
time_t rawtime = this->getEpochTime();
struct tm *ti;
ti = localtime(&rawtime);
int month = (ti->tm_mon + 1) < 10 ? 0 + (ti->tm_mon + 1) : (ti->tm_mon + 1);
return month;
}
// 获取日期
int NTPClient::getDate()
{
time_t rawtime = this->getEpochTime();
struct tm *ti;
ti = localtime(&rawtime);
int month = (ti->tm_mday) < 10 ? 0 + (ti->tm_mday) : (ti->tm_mday);
return month;
}
声明
声明 仅对次库加以扩展,以增强其实用性!!!
一个连接ESP8266的实例代码:
#include <NTPClient.h>
// change next line to use with another board/shield
#include <ESP8266WiFi.h>
//#include <WiFi.h> // for WiFi shield
//#include <WiFi101.h> // for WiFi 101 shield or MKR1000
#include <WiFiUdp.h>
const char *ssid = "<SSID>";
const char *password = "<PASSWORD>";
WiFiUDP ntpUDP;
// By default 'pool.ntp.org' is used with 60 seconds update interval and
// no offset
NTPClient timeClient(ntpUDP);
// You can specify the time server pool and the offset, (in seconds)
// additionally you can specify the update interval (in milliseconds).
// NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 3600, 60000);
void setup(){
Serial.begin(115200);
WiFi.begin(ssid, password);
while ( WiFi.status() != WL_CONNECTED ) {
delay ( 500 );
Serial.print ( "." );
}
timeClient.begin();
}
void loop() {
timeClient.update();
Serial.println(timeClient.getFormattedTime());
delay(1000);
//添加新函数
timeClient.getYear();//年
timeClient.getMonth();//月
timeClient.getDate();//日
}
Function documentation
getEpochTime
returns the Unix epoch, which are the seconds elapsed since 00:00:00 UTC on 1 January 1970 (leap seconds are ignored, every day is treated as having 86400 seconds). Attention: If you have set a time offset this time offset will be added to your epoch timestamp.
下载
© 版权声明
分享是一种美德,转载请保留原链接
发现评论条评论