RonanW
RonanW

Reputation: 11

How to convert a string Date in format xx/xx/xxxx or x/x/xxxx into integers of day, month & year using Stoi?

I'm trying to work out a function that should take a string in format xx/xx/xxxx OR x/x/xxxx and find the day, month 7 year components of the provided string and store them in day, month & year data variables.

I'm looking at using 'std::stoi', which I find straightforward to use for usual numbers, but am having trouble utilizing it for a date.

Upvotes: 1

Views: 1681

Answers (1)

scohe001
scohe001

Reputation: 15446

Why reinvent the wheel when you can use strptime()? You'll just have to be careful since the year will be recorded as the number of years since 1900 and the months are 0 indexed:

std::string date_string; //Assuming you have your date string here
tm tm_date;
char *ret = strptime(date_string.c_str(), "%d/%m/%Y", &tm_date);

if(!ret) {
    std::cout << "ERROR: Bad input date: " << date_string << std::endl;
    return 1; //or however you handle an error
}

std::cout << "You entered date with Year:" << (tm_date.tm_year + 1900)
     << ", Month:" << (tm_date.tm_mon + 1) 
     << ", Day:" << tm_date.tm_mday << std::endl;

See it run here: ideone

Upvotes: 1

Related Questions