45

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

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

4

4 回答 4

65

使用 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以供参考

于 2014-07-30T12:37:57.963 回答
61

您可以使用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
于 2012-06-26T18:22:52.263 回答
18

这应该有效:

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

根据需要进行修改。

于 2012-06-26T18:12:52.283 回答
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;
        }
于 2021-07-23T19:20:43.850 回答