2008-11-26 99 views

回答

18

使用strptime()解析時間爲struct tm,然後使用mktime()轉換爲time_t

+0

strptime()在Windows上不可用。有很好的選擇嗎? – 2008-11-26 19:17:15

+0

不知道在Windows上是不是一個好的選擇,有幾個可以使用的開源實現。或者,如果您知道日期將始終採用您提供的格式,則可以使用sscanf將其解析爲struct tm,然後使用mktime獲取time_t。 – 2008-11-26 19:23:46

+0

這是一個示例http://stackoverflow.com/a/11213640/1115059 – Jaydeep 2014-09-19 01:46:29

2

恐怕沒有任何標準的C/C++。 POSIX功能strptime可以轉換爲struct tm,然後可以使用mktime將其轉換爲time_t

如果您的目標是跨平臺兼容性,請更好地使用boost::date_time,它具有複雜的功能。

4

在沒有strptime你可以使用sscanf分析數據爲struct tm,然後調用mktime。不是最優雅的解決方案,但它會工作。

-1
static time_t MKTimestamp(int year, int month, int day, int hour, int min, int sec) 
{ 
    time_t rawtime; 
    struct tm * timeinfo; 

    time (&rawtime); 
    timeinfo = gmtime (&rawtime); 
    timeinfo->tm_year = year-1900 ; 
    timeinfo->tm_mon = month-1; 
    timeinfo->tm_mday = day; 
    timeinfo->tm_hour = hour; 
    timeinfo->tm_min = min; 
    timeinfo->tm_sec = sec; 
    timeinfo->tm_isdst = 0; // disable daylight saving time 

    time_t ret = mktime (timeinfo); 

    return ret; 
} 

static time_t GetDateTime(const std::string pstr) 
{ 
    try 
    { 
     // yyyy-mm-dd 
     int m, d, y, h, min; 
     std::istringstream istr (pstr); 

     istr >> y; 
     istr.ignore(); 
     istr >> m; 
     istr.ignore(); 
     istr >> d; 
     istr.ignore(); 
     istr >> h; 
     istr.ignore(); 
     istr >> min; 
     time_t t; 

     t=MKTimestamp(y,m,d,h-1,min,0); 
     return t; 
    } 
    catch(...) 
    { 

    } 
} 
1

請注意,在接受的答案中提到的strptime是不便攜的。下面是我使用字符串轉換爲std :: time_t的方便的C++代碼11:

static std::time_t to_time_t(const std::string& str, bool is_dst = false, const std::string& format = "%Y-%b-%d %H:%M:%S") 
{ 
    std::tm t = {0}; 
    t.tm_isdst = is_dst ? 1 : 0; 
    std::istringstream ss(str); 
    ss >> std::get_time(&t, format.c_str()); 
    return mktime(&t); 
} 

你可以這樣調用:

std::time_t t = to_time_t("2018-February-12 23:12:34"); 

你可以找到字符串格式參數here

1

的日期字符串,格式爲 「MM-DD-YY HH:MM:SS」 轉換效果最好的方式,以一個time_t的

限制代碼標準C庫函數是尋找反strftime()。要擴大@Rob總體思路,請使用sscanf()

"%n"使用以檢測完成掃描

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

附加代碼可以用於確保僅2位的時間戳部分,正值,間距等

注意:此假設「MM-DD -YY HH:MM:SS「是本地時間。