You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

ESP32C3上实现欧洲夏令时判断以修正日出日落时间的技术咨询

ESP32C3上实现欧洲夏令时判断以修正日出日落时间的技术咨询

我现在在给ESP32C3写Arduino风格的C代码,这块板子没有内置时钟,所以我通过NTP服务器获取网络时间。同时我还对接了天气服务器来获取本地天气信息,包括日出日落时间。

目前一切都正常,除了一个问题:天气服务器好像不考虑夏令时,返回的日出日落时间差了一个小时。

所以我写了一段代码来判断当前是否需要调整日出日落时间(用的是Arduino C),先明确一下欧洲的夏令时规则:

美国的夏令时从3月的第二个周日开始,11月的第一个周日结束。而英国和欧盟的夏令时则是从3月的最后一个周日开始,10月的最后一个周日结束。

以下是我写的夏令时判断代码:

char dayName[10];
char dayMonth[2];
char monthYear[2];

strftime(dayName,64,"%A", &timeinfo); // day of the week
strftime(dayMonth,64,"%d", &timeinfo); // day of the month
strftime(monthYear,64,"%B", &timeinfo); // month of the year

if (!strcmp(dayName, "Sunday")) {
  if (atoi(monthYear) == 10) {
    if (atoi(dayMonth) > 31 - 7) {
    // last Sunday of the month October, DST = false
      DST = false;
    }
  }
  if (atoi(monthYear) == 3) {
    if (atoi(dayMonth) > 31 - 7) {
      // last Sunday of the month March, DST = false
      DST = true;
    }
  }
}

我用下面的函数获取网络时间:

const char* ntpServer = "ch.pool.ntp.org";
const long  gmtOffset_sec = 3600;
const int   daylightOffset_sec = 0;

void getTime() {
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);

  if(!getLocalTime(&timeinfo)){
    //Serial.println("Failed to obtain time");
    return;
  }
}

这里有个“鸡生蛋”的问题:我没法在获取时间前设置夏令时偏移,因为得先拿到当前时间才能判断是否处于夏令时。

现在有两个问题想请教:

  1. 我这段判断夏令时的代码看起来合理吗?
  2. 有没有更好的实现方式?要注意这是ESP32C3,不是普通电脑,它本身没有内置的日期时间概念,完全靠NTP获取。

备注:内容来源于stack exchange,提问作者user3069232

火山引擎 最新活动