c# php delphi java 等各類語言 對字符串轉換爲日期 而後與當前日期進行比較 是很是容易的 由於有現成的函數可用php
標準 c++ 硬是找不到 合適的代碼可用java
因而c++
百度了不少 沒百出個結果c#
因而綜合網上資料 本身優化了下 直接拿來用 便可函數
time_t str_to_time_t(const string& ATime, const string& AFormat="%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_wday), &(tm_Temp.tm_yday)); 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); }
調用方法
string sEndTime ="2013-12-9"; string sTemp; time_t t_Now = NowTime(); time_t t_End = str_to_time_t(sEndTime); if (IsValidTime(t_End, t_Now)) { sTemp = "有效日期"; } else { sTemp = "時間過時"; }
++新增兩個通用方法 (新增date(double) to time_t) +time_t to string優化
string time_t_to_str(const time_t &ATime_t, const string& AFormat="%d-%d-%d") { char chRet[15]; string sRet; struct tm *p; try { p = localtime(&ATime_t); p->tm_year = p->tm_year + 1900; p->tm_mon = p->tm_mon + 1; sprintf(chRet, AFormat.c_str(), p->tm_year, p->tm_mon, p->tm_mday); sRet = chRet; return sRet; } catch(...) { return ""; } } time_t date_to_timet( double ADate, bool AClearDecimal= false) { if (AClearDecimal){ ADate = int(ADate); } return (time_t)((Adate-25569)*(24*60*60)-timezone + 0.5 ); }
// time_t dttime = date_to_timet(41618.9023, true);
[DATE]double(41618)=string("2013-12-10")