Here's the complete C implementation with date & time.
enum DateTimeFormat {
YearMonthDayDash, // "YYYY-MM-DD hh:mm::ss"
MonthDayYearDash, // "MM-DD-YYYY hh:mm::ss"
DayMonthYearDash // "DD-MM-YYYY hh:mm::ss"
};
//Uses specific datetime format and returns the Linux epoch time.
//Returns 0 on error
static time_t ParseUnixTimeFromDateTimeString(const std::wstring& date, DateTimeFormat dateTimeFormat)
{
int YY, MM, DD, hh, mm, ss;
struct tm when = { 0 };
int res;
if (dateTimeFormat == DateTimeFormat::YearMonthDayDash) {
res = swscanf_s(date.c_str(), L"%d-%d-%d %d:%d:%d", &YY, &MM, &DD, &hh, &mm, &ss);
}
else if (dateTimeFormat == DateTimeFormat::MonthDayYearDash) {
res = swscanf_s(date.c_str(), L"%d-%d-%d %d:%d:%d", &MM, &DD, &YY, &hh, &mm, &ss);
}
else if (dateTimeFormat == DateTimeFormat::DayMonthYearDash) {
res = swscanf_s(date.c_str(), L"%d-%d-%d %d:%d:%d", &DD, &MM, &YY, &hh, &mm, &ss);
}
//In case datetime was in bad format, returns 0.
if (res == EOF || res == 0) {
return 0;
}
when.tm_year = YY - 1900; //Years from 1900
when.tm_mon = MM - 1; //0-based
when.tm_mday = DD; //1 based
when.tm_hour = hh;
when.tm_min = mm;
when.tm_sec = ss;
//Make sure the daylight savings is same as current timezone.
time_t now = time(0);
when.tm_isdst = std::localtime(&now)->tm_isdst;
//Convert the tm struct to the Linux epoch
time_t converted;
converted = mktime(&when);
return converted;
}