日期/时间转换:字符串表示为time_t

如何将格式为"MM-DD-YY HH:MM:SS"的日期字符串转换为C或C ++中的time_t值?

使用strptime()将时间解析为struct tm ,然后使用mktime()转换为time_t

在没有strptime的情况下,您可以使用sscanf将数据解析为struct tm ,然后调用mktime 。 不是最优雅的解决方案,但它会起作用。

Boost的日期时间库应该有所帮助; 特别是你可能想看看http://www.boost.org/doc/libs/1_37_0/doc/html/date_time/date_time_io.html

我担心标准C / C ++中没有。 有POSIX函数strptime可以转换为struct tm ,然后可以使用mktime将其转换为time_t

如果您的目标是跨平台兼容性,那么最好使用boost::date_time ,它具有复杂的function。

将格式为“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”是当地时间

请注意,在接受的答案中提到的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"); 

您可以在此处找到字符串格式参数。

  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(...) { } }