patterncppMinor
Day elapsed since today from a given date
Viewed 0 times
elapsedtodaygivendatesincefromday
Problem
My function calculates days elapsed from the current date. Input is fixed. I will get vector.
Please comment on this.
Please comment on this.
static bool daysElapsed(const std::vector& vec,int& val)
{
std::string str(vec.begin(),vec.end());
char *pos;// whose value is set by the function to the next character in str after the numerical value.
int l = strtol(str.c_str(),&pos,10); // Its intention we don’t check till which length strtol converted
if ((errno == ERANGE && l == LONG_MAX) || l > INT_MAX) return false;
if ((errno == ERANGE && l == LONG_MIN) || l Do not rely on this time, Convert to local time first
localtime_s (&b,&rawtime);
time_t x = std::mktime(&a);
time_t y = std::mktime(&b);
if ( x != (std::time_t)(-1) && y != (std::time_t)(-1) ) // Ensure both time are valid
{
double difference = std::difftime(y, x) / (60 * 60 * 24);
std::cout << "difference = " << difference << " days" << std::endl;
}
else
return false;
return true;
}Solution
It's weird to take a
You never use the
You seem to expect the input in YYYYMMDD format, but you don't do any validation other than checking for overflow or underflow. There are plenty of 8-digit numbers that shouldn't be valid dates.
Unfortunately, the
When testing for the validity of
std::vector instead of a std::string. If you must take a std::vector, then make two overloaded versions of the function, where the vector variant calls the string variant.You never use the
val parameter. You probably meant to use it to return the computed result? However, the computed difference is a double.strtol() returns a long, but you assign it to an int. Then you check if that int exceeds INT_MAX or is less than INT_MIN — which is impossible by definition. Comparing an int with LONG_MAX and LONG_MIN is similarly nonsensical. Really, all you want to do is check whether errno is non-zero.You seem to expect the input in YYYYMMDD format, but you don't do any validation other than checking for overflow or underflow. There are plenty of 8-digit numbers that shouldn't be valid dates.
Unfortunately, the
localtime_s() function is Windows-only. POSIX has localtime_r(), whose arguments are in the other order, but Windows doesn't support it. You'll probably need an #ifdef _WIN32.When testing for the validity of
x and y, put the early-return failure case first. That's just a better pattern for error handling, because the successful case doesn't have to be indented another level.Context
StackExchange Code Review Q#32593, answer score: 4
Revisions (0)
No revisions yet.