best way to convert a date string, formatted as "MM-DD-YY HH:MM:SS", to a time_t
Restricting code to standard C library functions is looking for the inverse of strftime()
. To expand @Rob general idea, uses sscanf()
.
Use "%n"
to detect completed scan
time_t date_string_to_time(const char *date) {
struct tm tm = { 0 }; // Important, initialize all members
int n = 0;
sscanf(date, "%d-%d-%d %d:%d:%d %n", &tm.tm_mon, &tm.tm_mday, &tm.tm_year,
&tm.tm_hour, &tm.tm_min, &tm.tm_sec, &n);
// If scan did not completely succeed or extra junk
if (n == 0 || date[n]) {
return (time_t) -1;
}
tm.tm_isdst = -1; // Assume local daylight setting per date/time
tm.tm_mon--; // Months since January
// Assume 2 digit year if in the range 2000-2099, else assume year as given
if (tm.tm_year >= 0 && tm.tm_year < 100) {
tm.tm_year += 2000;
}
tm.tm_year -= 1900; // Years since 1900
time_t t = mktime(&tm);
return t;
}
Additional code could be used to insure only 2 digit timestamp parts, positive values, spacing, etc.
Note: this assume the "MM-DD-YY HH:MM:SS" is a local time.