2012-07-25 45 views
0

我正在使用下面的方法來驗證日期。 如何在字符串中格式化月份?DateTime Validation as 25-Jul-2012 15:08:23

bool CDateTime :: IsValidDate(char* pcDate) //pcDate = 25-Jul-2012 15:08:23 
{ 
    bool bVal = true; 
    int iRet = 0; 
    struct tm tmNewTime; 

    iRet = sscanf_s(pcDate, "%d-%d-%d %d:%d:%d", &tmNewTime.tm_mon, &tmNewTime.tm_mday, &tmNewTime.tm_year, &tmNewTime.tm_hour, &tmNewTime.tm_min, &tmNewTime.tm_sec); 
    if (iRet == -1) 
     bVal = false; 

    if (bVal == true) 
    { 
     tmNewTime.tm_year -= 1900; 
     tmNewTime.tm_mon -= 1; 
     bVal = IsValidTm(&tmNewTime); 
    } 
    return bVal; 

} 
+0

fyi,'struct tm tmNewTime;'中的'struct'在C++中是多餘的。 – chris 2012-07-25 06:20:29

+0

您在sscanf_s語句中混合了「tm_mon」和「tm_year」。 – 2012-07-25 06:26:01

+0

也許看看http://stackoverflow.com/questions/308390/convert-a-string-to-a-date-in-c? – 2012-07-25 06:29:26

回答

1

使用strptime

#include <time.h> 
char *str = "25-Jul-2012 15:08:23"; 
struct tm tm; 
if (strptime (str, "%d-%b-%Y %H:%M:%S", &tm) == NULL) { 
    /* Bad format !! */ 
} 
+0

我已包含它說的strptime標識符沒有找到 – user662285 2012-07-25 06:37:46

+0

你正在做什麼平臺? – perreal 2012-07-25 06:39:50

+0

Windows ......... – user662285 2012-07-25 06:55:51

-1

這樣做的C++ 11的方式是:

注:流I/O操縱std::put_time還沒有完全實現在所有編譯器中。 GCC 4.7.1沒有它。

+0

這個問題是關於一個日期的字符串驗證,而不是流出一個日期爲字符串。 – 2012-07-25 06:43:55

+0

@JakobS。引用這個問題:「如何在字符串中格式化月份?」 OP_states_他想驗證一個日期,但是_asks_關於格式化。 – 2012-07-25 06:47:21

+0

好吧,你是對的 - 標題並不真正反映這個問題。 – 2012-07-25 06:49:29