I have been given a date, Which I am taking as an input like (day, month, year): 12, 03, 87.
Now I need to find out the date after n days.<
Can you please tell me any good logic which works faster and have less complexity.
If this exact thing is indeed a performance critical part of your application, you're likely doing something wrong. For the sake of clarity and correctness, you should stick to the existing solutions. Select the one that is most appropriate to your development environment.
The C approach:
#include
#include
int main()
{
/* initialize */
int y=1980, m=2, d=5;
struct tm t = { .tm_year=y-1900, .tm_mon=m-1, .tm_mday=d };
/* modify */
t.tm_mday += 40;
mktime(&t);
/* show result */
printf("%s", asctime(&t)); /* prints: Sun Mar 16 00:00:00 1980 */
return 0;
}
The C++ without using Boost approach:
#include
#include
int main()
{
// initialize
int y=1980, m=2, d=5;
std::tm t = {};
t.tm_year = y-1900;
t.tm_mon = m-1;
t.tm_mday = d;
// modify
t.tm_mday += 40;
std::mktime(&t);
// show result
std::cout << std::asctime(&t); // prints: Sun Mar 16 00:00:00 1980
}
The Boost.Date_Time approach:
#include
#include
int main()
{
using namespace boost::gregorian;
// initialize
date d(1980,2,5);
// modify
d += days(40);
// show result
std::cout << d << '\n'; // prints: 1980-Mar-16
}