r/esp32•
emaayan

trying to set the time on esp32 but getting a weird result

hi..

i have the following code:

but for some reason i always get:

586454-01-17 21:21:49

not sure why..

const char *time_str="1899-12-31 13:20:00";

struct tm tm;

memset(&tm, 0, sizeof(struct tm));

`setenv("TZ", "GMT", 1);`

tzset();

// Parse the input string

if (strptime(time_str, "%Y-%m-%d %H:%M:%S", &tm) == NULL) {

ESP_LOGE(TAG, "Invalid time format. Use hh:mm:ss\n");

}else{

	`time_t t = mktime(&tm);`		

	`char tmbuf[64];`

	`strftime(tmbuf, sizeof tmbuf, "%Y-%m-%d %H:%M:%S", &tm);`

	

	`ESP_LOGI(TAG,"Read Time %s",tmbuf);`

	`ESP_LOGI(TAG,"Parsed TIme: %s ",asctime(&tm));`

	`ESP_LOGI(TAG,"Made Time %s",ctime(&t));`

if (t == -1) {

ESP_LOGE(TAG, "Failed to conver time");

}else{

		`struct timeval tv={.tv_sec=t,.tv_usec=0};`

		

		`int r =settimeofday(&tv,NULL);`

		`if (r!=0){`

ESP_LOGI(TAG,"Error setting time of Day %d",r);

		`}else{`

struct tm *nowtm_before=gmtime(&tv.tv_sec);

char tmbuf_before[64];

strftime(tmbuf_before, sizeof tmbuf_before, "%Y-%m-%d %H:%M:%S", nowtm_before);

ESP_LOGI(TAG,"Time before is %s",tmbuf_before);

		`}`

		

struct timeval p={.tv_sec=0,.tv_usec=0};

r =gettimeofday(&p,NULL);

//p.tv_sec= p.tv_sec* 1000000L + (int64_t)p.tv_usec;//p.tv_sec / 1000000U;

if (r!=0){

ESP_LOGI(TAG,"Error getting time of Day %d",r);

		`}else{`

struct tm *nowtm= gmtime(&p.tv_sec);

char tmbuf[64];

strftime(tmbuf, sizeof tmbuf, "%Y-%m-%d %H:%M:%S", nowtm);

ESP_LOGI(TAG,"Time is %s",tmbuf);

		`}`

		

time_t now;

char strftime_buf[64];

struct tm timeinfo;

time(&now);

struct tm *nowtm_a=gmtime(&now);

strftime(strftime_buf, sizeof(strftime_buf), "%c", nowtm_a);

ESP_LOGI(TAG, "The current date/time in GMT is: %s", strftime_buf);

//ESP_LOGI(TAG,"TIme %s",ctime(&p));

	`}`	

`}`

Posted Jul 29, 2024, 7:26 AM UTC

15
Loading comments…