首页 > 解决方案 > 来自 NTP 服务器的日期

问题描述

我在我的 Arduino 代码和 ESP8266 板上使用 NTP 服务器。我正在使用“Serial.println(timeClient.getFormattedTime());” 但该功能只打印时间而不是日期(DD-MM-YYYY),我需要日期..

这是我的代码:

#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     = "----------";
const char *password = "**********";

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);

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);
}

谢谢

标签: arduinoesp8266ntp

解决方案


如果您查看该库的源代码,您会发现所有 getFormattedtime 函数都应该输出。

我在该库中没有看到该日期的函数。在我看来,您必须使用 getEpochTime 获取纪元时间并自己计算日期。互联网上应该有很多关于如何将纪元时间转换为日期的示例。

Time 库具有将 unix 时间转换为月日和年的功能。


推荐阅读