Page 1 of 1

Problem with mktime() and difftime()

Posted: Sat Apr 30, 2022 5:31 pm
by Thanh Quang
Hi, I had a problem with mktime() and difftime(). I need to calculate time interval between now and a specific time. I used LOGI to log my local_time and alarm_time, when I calculate time interval between someday in the same month, it works fine. But when I use difftime() to calculate time interval between 23:59:00 04/30/2022 and 07:00:00 05/01/2022, it likely add 86400 ( = 24*60*60 secs) to result. I tested for other month and it did too.
Please help me solve this problem.
Sorry for my English :D
  1. time_t i2clocaltime = mktime(&local_time);
  2.   time_t alrmtime = mktime(&alarm_time);
  3.   double remain_time = difftime(alrmtime,i2clocaltime);
  4.   ESP_LOGI(TAG,"Alarm time %04d-%02d-%02d %02d:%02d:%02d",alarm_time.tm_year,alarm_time.tm_mon,alarm_time.tm_mday,alarm_time.tm_hour,alarm_time.tm_min,alarm_time.tm_sec);
  5.   ESP_LOGI("Remain time","time %f",remain_time);
  1. I (10623) MQTT_DAQ: today 2022-04-30 23:59:13
  2. I (10623) MQTT_DAQ: Alarm time 2022-05-01 07:00:00
  3. I (10633) Remain time: time 111647.000000
  4. I (10643) MQTT_DAQ: File written
  5. I (150633) MQTT_DAQ: File written

Re: Problem with mktime() and difftime()

Posted: Sun May 01, 2022 1:01 am
by ESP_Sprite
That is curious behavior... I don't think the issue is ESP-IDF here, I tested it on Linux and the behaviour is the same.

EDIT: I think I found it. tm->mon is zero-based, so a month of 0 is January, 1 is February etc. You were calculating the difference between May 30 and Jun 1, and there's indeed a day between those.

Re: Problem with mktime() and difftime()

Posted: Sun May 01, 2022 3:24 pm
by Thanh Quang
Oh, thanks. I didn't know this, I will test it again soon and post feedback :lol: