Could anyone please help me convert and string into Year and Month (not day)? The code I use for converting a string into a proper year-month-day is as follows:
bool get_time(const std::string& s, time_t& time)
{
tm date;
date.tm_isdst = 0;
std::istringstream iss(s);
std::string line;
char c;
// Read date as a whole string up to '-' (yyyymmdd)
if(!(std::getline(iss, line, ' ') >> c))
{
returnfalse;
}
if(line.size() != 10)
{
returnfalse; // illegal data, should be 8 characters
}
// pick out pieces of date
if(!(std::istringstream(line.substr(0, 4)) >> date.tm_year))
{
returnfalse;
}
if(!(std::istringstream(line.substr(5, 2)) >> date.tm_mon))
{
returnfalse;
}
if(!(std::istringstream(line.substr(8, 2)) >> date.tm_mday))
{
returnfalse;
}
// read time
if(!(iss >> date.tm_hour >> c))
{
returnfalse;
}
if(!(iss >> date.tm_min >> c))
{
returnfalse;
}
if(!(iss >> date.tm_sec >> c))
{
returnfalse;
}
// adjust to struct tm spec bounds
date.tm_mon -= 1; // needs to be 0-11 (not 1-12)
date.tm_year -= 1900;
time = mktime(&date);
returntrue;
}
How do I use it for converting a string like 1209 which means year 2012 and month september. I want to find which one is the smallest/near time e-g 1103(year-2011 and month-March) is nearer than 1209(year-2012 and month-September) and I want the method below to return the near time.