如何在c ++中将包含time的字符串变量转换为time_t类型?

时间:2012-06-26 18:04:47

标签: c++ time

我有一个包含 hh:mm:ss格式 时间的字符串变量。如何将其转换为time_t类型?例如:string time_details =“16:35:12”

另外,如何比较两个包含时间的变量,以便确定哪个是最早的? 例如:string curr_time =“18:35:21”      string user_time =“22:45:31”

4 个答案:

答案 0 :(得分:49)

您可以使用strptime(3)来解析时间,然后mktime(3)将其转换为time_t

const char *time_details = "16:35:12";
struct tm tm;
strptime(time_details, "%H:%M:%S", &tm);
time_t t = mktime(&tm);  // t is now your desired time_t

答案 1 :(得分:47)

使用C ++ 11,您现在可以

struct std::tm tm;
std::istringstream ss("16:35:12");
ss >> std::get_time(&tm, "%H:%M:%S"); // or just %T in this case
std::time_t time = mktime(&tm);

请参阅std::get_timestrftime以供参考

答案 2 :(得分:13)

这应该有效:

int hh, mm, ss;
struct tm when = {0};

sscanf_s(date, "%d:%d:%d", &hh, &mm, &ss);


when.tm_hour = hh;
when.tm_min = mm;
when.tm_sec = ss;

time_t converted;
converted = mktime(&when);

根据需要进行修改。

答案 3 :(得分:0)

这是带有日期和时间的完整 C 实现。

        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;
        }