Description
A sample of how use C++ localtime/mktime to implement datetime calculation, for example plus/minus a few days, months, years, etc.
Source Code:
#include <time.h> #include <iomanip> #include <iostream> void printtm(const char * prefix, tm * tp) { std::cout << prefix; std::cout << std::setw(4) << std::setfill('0') << tp->tm_year + 1900; // year std::cout << "/"; std::cout << std::setw(2) << std::setfill('0') << tp->tm_mon + 1; // month std::cout << "/"; std::cout << std::setw(2) << std::setfill('0') << tp->tm_mday; // day std::cout << " "; std::cout << std::setw(2) << std::setfill('0') << tp->tm_hour; // hour std::cout << ":"; std::cout << std::setw(2) << std::setfill('0') << tp->tm_min; // minute std::cout << ":"; std::cout << std::setw(2) << std::setfill('0') << tp->tm_sec; // second std::cout << std::endl; } int main(int argc, char * argv[]) { time_t t = time(NULL); tm * tp = localtime(&t); printtm("today :", tp); tp->tm_mday += 2; mktime(tp); printtm("+2 days :", tp); // 2 days later tp->tm_mon += 2; mktime(tp); printtm("+2 months :", tp); // 2 months later tp->tm_year -= 2; mktime(tp); printtm("-2 year :", tp); // 2 years before return 0; }
Compile and execute:
$ g++ tt.cpp $ ./a.out today :2015/12/29 04:16:25 +2 days :2015/12/31 04:16:25 +2 months :2016/03/02 04:16:25 -2 year :2014/03/02 04:16:25
Limitation:
Function localtime() is not thread-unsafe, it uses an internal memory space to keep the datetime data structure, when multiply calling localtime(..) they overwrite the same memory space.
So localtime() cannot be shared among multiply threads.
The end