ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

esp-idf手动设置系统时间

2021-12-10 11:03:02  阅读:752  来源: 互联网

标签:timeinfo int 手动 esp tm time idf now strftime


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

System Time - ESP32 - — ESP-IDF 编程指南 v4.3.1 文档icon-default.png?t=LA92https://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 文档icon-default.png?t=LA92https://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 · GitHubicon-default.png?t=LA92https://github.com/fbiego/ESP32Time/blob/main/ESP32Time.cpp How can I set the date / time? - ESP32 ForumEspressif ESP32 Official Forumhttps://www.esp32.com/viewtopic.php?t=6043

标签:timeinfo,int,手动,esp,tm,time,idf,now,strftime
来源: https://blog.csdn.net/u011738895/article/details/121850283

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有