esp-idf手动设置系统时间

官方提到使用ntp同步时间,后自动设置了时间。

System Time - ESP32 - — ESP-IDF 编程指南 v4.3.1 文档esp-idf手动设置系统时间https://docs.espressif.com/projects/esp-idf/zh_CN/v4.3.1/esp32/api-reference/system/system_time.html使用了函数settimeofday().

To set the current time, you can use the POSIX functions settimeofday() and adjtime()

这里直接手动设置时间,参考arduino第三方库esp32time的写法。

#include <time.h>
#include <sys/time.h>
//houyawei
void setTime(int sc, int mn, int hr, int dy, int mt, int yr) {
    // seconds, minute, hour, day, month, year $ microseconds(optional)
    // ie setTime(20, 34, 8, 1, 4, 2021) = 8:34:20 1/4/2021
    struct tm t = {0};        // Initalize to all 0's
    t.tm_year = yr - 1900;    // This is year-1900, so 121 = 2021
    t.tm_mon = mt - 1;
    t.tm_mday = dy;
    t.tm_hour = hr;
    t.tm_min = mn;
    t.tm_sec = sc;
    time_t timeSinceEpoch = mktime(&t);
    //   setTime(timeSinceEpoch, ms);
    struct timeval now = { .tv_sec = timeSinceEpoch };
    settimeofday(&now, NULL);
//houyawei
}

调用的时候,直接

setTime(20,34,8,1,4,2021);

读取可以直接按照官方写的例子

time_t now;
char strftime_buf[64];
struct tm timeinfo;

time(&now);
// Set timezone to China Standard Time
setenv("TZ", "CST-8", 1);
tzset();

localtime_r(&now, &timeinfo);
strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
//ESP_LOGI(TAG, "The current date/time in Shanghai is: %s", strftime_buf);
puts(strftime_buf);
//也可以只取出年月日等参数
/×
timeinfo.tm_year
timeinfo.tm_mon  
timeinfo.tm_mday
timeinfo.tm_hour
timeinfo.tm_min
timeinfo.tm_sec
houyawei
×/

参考:

System Time - ESP32 - — ESP-IDF 编程指南 v4.3.1 文档esp-idf手动设置系统时间https://docs.espressif.com/projects/esp-idf/zh_CN/v4.3.1/esp32/api-reference/system/system_time.html

ESP32Time/ESP32Time.cpp at main · fbiego/ESP32Time · GitHubesp-idf手动设置系统时间https://github.com/fbiego/ESP32Time/blob/main/ESP32Time.cpp How can I set the date / time? - ESP32 ForumEspressif ESP32 Official Forumesp-idf手动设置系统时间https://www.esp32.com/viewtopic.php?t=6043

上一篇:TF-IDF笔记整理


下一篇:无监督关键短语的生成问题博客11--tfidf.py的分析