【问题标题】:DateTime Validation as 25-Jul-2012 15:08:23日期时间验证为 25-Jul-2012 15:08:23
【发布时间】:2012-07-25 06:19:36
【问题描述】:

我正在使用以下方法来验证日期。 如何在字符串中格式化月份?

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;

}

【问题讨论】:

  • fyi,struct tm tmNewTime; 中的 struct 在 C++ 中是多余的。
  • 您在 sscanf_s 语句中混淆了“tm_mon”和“tm_year”。
  • 您是询问如何进行实际验证,还是询问如何进行格式化?

标签: c++ windows


【解决方案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 !! */
}

【讨论】:

  • 我已包含 位,表示未找到 strptime 标识符
【解决方案2】:

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 没有它。

【讨论】:

  • 问题是关于以字符串形式给出的日期的验证,而不是关于以字符串形式输出日期。
  • @JakobS。引用问题:“如何在字符串中格式化月份?” OP 声明他想要验证日期,但询问格式。
  • 好的,你是对的 - 标题并没有真正反映问题。
猜你喜欢
  • 1970-01-01
  • 2010-10-04
  • 2017-01-26
  • 2012-07-08
  • 2019-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多