Processing time in c/c++ — solution for year 2038 problem in 32 bit machine

Prince Francis
2 min readAug 8, 2020

How to find the difference between 2 dates, which are in string format ?

The solution was very simple, after execution of below code snippet we will get the required result in the variable dates

tm start_parsed = {};
strptime("2020-01-21 05:00", "%Y-%m-%d %H:%M", &start_parsed)
tm end_parsed = {};
strptime("2038-12-23 05:00", "%Y-%m-%d %H:%M", &end_parsed)
time_t start = mktime(&start_parsed);
time_t end = mktime(&end_parsed);
int dates = difftime(end, start) / (60 * 60 * 24);

It worked fine, till customer installed the library in a 32 bit ubuntu device. We tested the library in 64 bit ubuntu device, so we couldn’t identify these issue. Since I am from Java background, I never forecasted such issues. The library works in our device, but failed in some of the customer devices. You could find the details of issue from here.

I solved the issue by using the library https://github.com/evalEmpire/y2038/

I followed the below steps and solved the issue

1. Download the library from the github repo
2. Copy/paste the files time64.c, time64.h, time64_config.h, time64_limits.h into our project
3. Uncomment the line #define USE_TM64 in the file time64_config.h
4. Include the file #include "time64.h"

Once we added the files, use the below code snippet.

tm start_parsed = {};
strptime("2020-01-21 05:00", "%Y-%m-%d %H:%M", &start_parsed)
TM start_parsed64 = {};
start_parsed64.tm_year = start_parsed.tm_year;
start_parsed64.tm_mon = start_parsed.tm_mon;
start_parsed64.tm_mday = start_parsed.tm_mday;
tm end_parsed = {};
strptime("2038-12-23 05:00", "%Y-%m-%d %H:%M", &end_parsed)
TM end_parsed64 = {};
end_parsed64.tm_year = end_parsed.tm_year;
end_parsed64.tm_mon = end_parsed.tm_mon;
end_parsed64.tm_mday = end_parsed.tm_mday;
int dates = diff_dates(end_parsed64, start_parsed64)

the difftime won’t work with new data type, so I created new function diff_dates as follows.

Link to the github repo : https://github.com/princekf/cpp_difference_between_tow_dates

--

--