Home > front end >  How to check if given year, month, day and time format is valid in C ?
How to check if given year, month, day and time format is valid in C ?

Time:06-27

I am working on an application where the log files will be named in the format "YYYYMMDDHHMM_****.gz". The log file contains YYYY (year), MM (month), DD (day), HH (hours) and MM (minutes). 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. But it is not returning -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.

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. But time_t is not giving -1 for invalid date time format. 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?

CodePudding user response:

You need to check if std::get_time itself fails. The failing operation is the conversion, not the construction of a time_t value from the resulting struct tm.

The sample code on cppreference.com gives a very easy to follow example of how to do that:

    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.

  • Related