Question

I can write a function to parse the string date, but I feel like I am re-inventing the wheel here. Is there a faster, perhaps built in C++ way to get from a string date of this format: 1/4/2000 to a more easy to use int like 20000104?

Was it helpful?

Solution

Unless you need your built-in C++ way to do validation as well, the "obvious" parse is:

int parseDate(const std::string &input) {
    int month;
    int day;
    int year;
    if (std::sscanf(input.c_str(), "%d/%d/%d", &month, &day, &year) != 3) {
        // handle error
    } else {
        // check values to avoid int overflow if you can be bothered
        return 10000 * year + 100 * month + day;
    }
}

You can use stream extractors instead of sscanf if you want to write several lines of code type safety.

There's certainly nothing in the standard library to do the 10000 * year + 100 * month + day for you. If you're not wedded to that exact value, you just want an integer in the correct order, then you could look at whether your platform has a function to tell you the so-called "Julian day".

OTHER TIPS

The standard library function is strptime(), not sure how "clean" that is considered to be in C++, though.

If you're okay with strptime(), here's how you would use it for your case:

struct tm when;

strptime("1/4/2000", "%m/%d/%y", &tm); // Note: should check return value.
const int sortable = 10000 * tm.tm_year + 100 * tm.tm_month + tm.tm_day;

Of course, you can use Boost if you want; the relevant corner seems to be Posix Time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top