简体   繁体   English

如何检查给定的年、月、日和时间格式在 C++ 中是否有效?

[英]How to check if given year, month, day and time format is valid in C++?

I am working on an application where the log files will be named in the format "YYYYMMDDHHMM_****.gz".我正在开发一个应用程序,其中日志文件将以“YYYYMMDDHHMM_****.gz”格式命名。 The log file contains YYYY (year), MM (month), DD (day), HH (hours) and MM (minutes).日志文件包含 YYYY(年)、MM(月)、DD(日)、HH(小时)和 MM(分钟)。 My class constructor needs to check if the file name is valid (whether the year, month, day and time are valid or not).我的类构造函数需要检查文件名是否有效(年月日时间是否有效)。 I thought by passing these values to time_t structure, it will return -1 for invalid values.我认为通过将这些值传递给 time_t 结构,它将为无效值返回 -1。 But it is not returning -1.但它没有返回-1。

Below is the program.下面是程序。

#include <iostream>
#include <iomanip>
#include <ctime>
#include <sstream>

int main() {
    
    struct tm tm{};
    std::istringstream iss("2018 12 22 00:26:00");
    //std::istringstream iss("2018 12 aa 00:26:00"); --> THIS IS NOT -1
    iss >> std::get_time(&tm, "%Y %m %d %H:%M:%S");
    time_t time = mktime(&tm);
    std::cout << time << std::endl;
    std::cout << std::ctime(&time) << std::endl;

    return 0;
}

O/P:输出/输出:

1545438360
Sat Dec 22 00:26:00 2018

But If I give date as "2018 12 aa 00:26:00" (month : aa which is invalid), still it is printing some valid o/p.但是,如果我将日期指定为“2018 12 aa 00:26:00” (月份:aa 无效),它仍然会打印一些有效的 o/p。

O/P:输出/输出:

1543536000
Fri Nov 30 00:00:00 2018

I need to discard the files which are having file names in the format ""YYYYMMDDHHMM_****.gz"" and which are 14 days old in a directory.我需要丢弃文件名格式为“YYYYMMDDHHMM_****.gz”且在目录中已有 14 天的文件。 But time_t is not giving -1 for invalid date time format.但是 time_t 没有为无效的日期时间格式提供 -1。 Can any one please let me know if there is any way to check if the given date is valid or do I need to check manually?任何人都可以让我知道是否有任何方法可以检查给定日期是否有效,或者我需要手动检查吗?

You need to check if std::get_time itself fails.您需要检查std::get_time本身是否失败。 The failing operation is the conversion, not the construction of a time_t value from the resulting struct tm .失败的操作是转换,而不是从结果struct tm构造time_t值。

The sample code on cppreference.com gives a very easy to follow example of how to do that: cppreference.com 上的示例代码提供了一个非常容易遵循的示例,说明如何做到这一点:

    ss >> std::get_time(&t, "%Y-%b-%d %H:%M:%S");
    if (ss.fail()) {
        std::cout << "Parse failed\n";

When std::get_time fails it sets the input stream into a failed state, so all you do is check for that.std::get_time失败时,它将输入流设置为失败状态,因此您要做的就是检查它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM