简体   繁体   English

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

[英]How to convert a string variable containing time to time_t type in c++?

I have a string variable containing time in hh:mm:ss format .我有一个字符串变量,其中包含hh:mm:ss 格式的时间。 How to convert it into time_t type?如何将其转换为 time_t 类型? eg: string time_details = "16:35:12"例如:字符串 time_details = "16:35:12"

Also, how to compare two variables containing time so as to decide which is the earliest?另外,如何比较两个包含时间的变量,以确定哪个是最早的? eg: string curr_time = "18:35:21" string user_time = "22:45:31"例如:字符串 curr_time = "18:35:21" 字符串 user_time = "22:45:31"

With C++11 you can now do使用 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);

see std::get_time and strftime for reference请参阅std::get_timestrftime以供参考

You can use strptime(3) to parse the time, and then mktime(3) to convert it to a time_t :您可以使用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

This should work:这应该有效:

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

Modify as needed.根据需要进行修改。

Here's the complete C implementation with date & time.这是带有日期和时间的完整 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;
        }

use strptime .使用strptime

struct tm tm;
memset(&tm, 0, sizeof(tm));
char *res = strptime(strtime.c_str(), format.c_str(), &tm);
if (res == nullptr) {
    // err process
}
ti = mktime(&tm);

Must init tm, and check the return value.必须初始化tm,并检查返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM