转载:https://www.cnblogs.com/maphc/p/3462952.html
#include <iostream> #include <time.h> using namespace std; time_t str_to_time_t(const string& ATime, const string& AFormat = "%d-%d-%d %d:%d:%d") { struct tm tm_Temp; time_t time_Ret; try { int i = sscanf(ATime.c_str(), AFormat.c_str(),// "%d/%d/%d %d:%d:%d" , &(tm_Temp.tm_year), &(tm_Temp.tm_mon), &(tm_Temp.tm_mday), &(tm_Temp.tm_hour), &(tm_Temp.tm_min), &(tm_Temp.tm_sec)); tm_Temp.tm_year -= 1900; tm_Temp.tm_mon--; //如果精确到秒就把下面四行注释掉;如果精确到天就把下面四行代码放开 //tm_Temp.tm_hour = 0; //tm_Temp.tm_min = 0; //tm_Temp.tm_sec = 0; //tm_Temp.tm_isdst = 0; time_Ret = mktime(&tm_Temp); return time_Ret; } catch (...) { return 0; } } time_t NowTime() { time_t t_Now = time(0); struct tm* tm_Now = localtime(&t_Now); //如果精确到秒就把下面四行注释掉;如果精确到天就把下面四行代码放开 //tm_Now->tm_hour = 0; //tm_Now->tm_min = 0; //tm_Now->tm_sec = 0; return mktime(tm_Now); } bool IsValidTime(const time_t& AEndTime, const time_t& ANowTime) { return (AEndTime >= ANowTime); } int main() { string sEndTime = "2019-5-11 17:38:59"; time_t t_Now = NowTime(); time_t t_End = str_to_time_t(sEndTime); if (IsValidTime(t_End, t_Now)) { cout<< "有效日期" << endl; } else { cout << "时间过期" << endl; } return 0; }