日期时间验证截止到2012年7月25日15:08:23

DateTime Validation as 25-Jul-2012 15:08:23

本文关键字:25日 7月 2012年 验证 时间 日期      更新时间:2023-10-16

我使用下面的方法来验证Date。如何格式化字符串中的月份?

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

使用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 !! */
}

C++11实现这一点的方法是:

#include <iostream>
#include <iomanip>
#include <ctime>
#include <chrono>
int main()
{
    auto now = std::chrono::system_clock::now();
    auto now_c = std::chrono::system_clock::to_time_t(now);
    std::cout << "Now is " << std::put_time(std::localtime(&now_c), "%d-%b-%Y %H:%M:%S") << 'n';
}

注意:流I/O操纵器std::put_time尚未在所有编译器中完全实现。例如,GCC 4.7.1没有。