I want to convert a given time into epoch(time_t) and vice versa. can anyone tell what is the routine or algorithm for this?
Thanks
Update>
To convert a struct tm to a time_t, use mktime. To convert a time_t to a struct tm, use either gmtime or localtime.
Sample:
#include
#include
int main () {
std::time_t now = std::time(0);
std::tm *now_tm = gmtime(&now);
std::tm tomorrow_tm(*now_tm);
tomorrow_tm.tm_mday += 1;
tomorrow_tm.tm_hour = 0;
tomorrow_tm.tm_min = 0;
tomorrow_tm.tm_sec = 0;
std::time_t tomorrow = std::mktime(&tomorrow_tm);
double delta = std::difftime(tomorrow, now);
std::cout << "Tomorrow is " << delta << " seconds from now.\n";
}
#include
#include
#include
// Display the difference between now and 1970-01-01 00:00:00
// On my computer, this printed the value 1330421747
int main () {
std::tm epoch_strt;
epoch_strt.tm_sec = 0;
epoch_strt.tm_min = 0;
epoch_strt.tm_hour = 0;
epoch_strt.tm_mday = 1;
epoch_strt.tm_mon = 0;
epoch_strt.tm_year = 70;
epoch_strt.tm_isdst = -1;
std::time_t basetime = std::mktime(&epoch_strt);
std::time_t curtime = std::time(0);
long long nsecs = std::difftime(curtime, basetime);
std::cout << "Seconds since epoch: " << nsecs << "\n";
assert(nsecs > 42ll * 365 * 24 * 60 * 60);
}