0 votes
18 views

I need to convert a formatted date string to Unix time (time_t) in ESP-IDF.

I need to obtain the production (compilation) date using the esp_app_get_description() function, which returns an esp_app_desc_t structure containing application-specific information. This contains time and date fields from which I can obtain the production date string.

The formatted date and time are stored separately in the date and time fields, respectively, and have the following format:

17:25:41
Oct 24, 2025

I know that I need to merge those fields first, but I don't know how to convert this date string to time_t.

by (1.4k points) | 18 views

1 Answer

0 votes

You should use the strptime() for this purpose. It converts a string representation of time to a time tm structure. strptime() works as the oppsite of strftime() function. Now let's see how the date obtained from the esp_app_desc_t can be converted to unix time as time_t.

  1. Merge the date and time fields of esp_app_desc_t into a buffer:

     char buf[32];
    
     const esp_app_desc_t *app_desc = esp_app_get_description();
    
     // Merge date and time fields
     strncpy(buf, app_desc->date, sizeof(buf));
     strncat(buf, " ", sizeof(buf) - strlen(buf) - 1);
     strncat(buf, app_desc->time, sizeof(buf) - strlen(buf) - 1);
    
  2. Then convert it to time_t

     time_t prod_time;
     struct tm prod_tm;
     memset(&prod_tm, 0, sizeof(prod_tm));
     strptime(buf, "%b %d %Y %H:%M:%S", &prod_tm);
     prod_time = mktime(&prod_tm);
    

Here is the full snippet:

#include <time.h>
#include <string.h>
#include "esp_log.h"

void production_time_to_ctime(void)
{
    char buf[32];
    time_t prod_time;

    const esp_app_desc_t *app_desc = esp_app_get_description();

    // Merge date and time fields
    strncpy(buf, app_desc->date, sizeof(buf));
    strncat(buf, " ", sizeof(buf) - strlen(buf) - 1);
    strncat(buf, app_desc->time, sizeof(buf) - strlen(buf) - 1);

    ESP_LOGI(TAG, "production_time_init: merged time string: %s", buf);

    struct tm prod_tm;
    memset(&prod_tm, 0, sizeof(prod_tm));
    strptime(buf, "%b %d %Y %H:%M:%S", &prod_tm);
    prod_time = mktime(&prod_tm);
    ESP_LOGI(TAG, "production_time_init: unix time: %lld", prod_time);
}

References

by (1.4k points)
Welcome to Kozmotronik Q&A, where you can ask questions and receive answers from other members of the community.