the scenario is: I get datetime in format \"YYYY-MM-DD HH:MM:SS\" with libexif. To minimize the saving cost, I wanna convert the datetime to unix timestamp or alike which on
Linux supports the getdate() function, which I think is more practical than calling strptime() directly. This is because the getdate() function automatically checks many formats for you. It is an equivalent to calling strptime() with various formats until the function works or all formats were tested.
// setenv() should be called only once
setenv("DATEMSK", "/usr/share/myprog/datemsk.fmt", 0);
// convert a date
struct tm * t1(getdate("2018-03-31 14:35:46"));
if(t1 == nullptr) ...handle error...
time_t date1(timegm(t1));
// convert another date
struct tm * t2(getdate("03/31/2018 14:35:46"));
if(t2 == nullptr) ...handle error...
time_t date2(timegm(t2));
Note: timegm() is similar to mktime() except that it ignores the locale and uses UTC. In most cases that's the right way to convert your dates.
The datemsk.fmt file would include at least these two formats to support the above dates:
%Y-%b-%d %H:%M:%S
%b/%d/%Y %H:%M:%S
The number of supported formats is not limited, although you may not want to have too many. It's going to be rather slow if you have too many formats. You could also dynamically manage your formats and call strptime() in a loop.
Linux also offers a getdate_r() function which is thread safe.
Man Page: http://pubs.opengroup.org/onlinepubs/7908799/xsh/getdate.html