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
epoch_strt.tm_sec = 0;
epoch_strt.tm_min = 0;
epoch_strt.tm_hour = 0;
epoch_strt.tm_mday = 1;
epoch_strt.tm_mon = 1;
epoch_strt.tm_year = 70;
epoch_strt.tm_isdst = -1;
double nsecs = difftime(curtime, basetime);//current time from system, I converrting it to struct tm
but this always return 32399 for some reason.
You should cast it to a long int
instead of int
.
long int t = static_cast<long int> (time(NULL));
An int
might not be enough to hold the time, for example, on my platform, time_t
is a typedef
of __int64
.
Whatever you're doing with time_t
, you'll probably be best off using the <chrono>
library. Then you can convert to and from time_t
, if necessary. Hopefully you can just do what you need in <chrono>
#include <chrono>
int main() {
auto a = std::chrono::system_clock::now()
time_t b = std::chrono::system_clock::to_time_t(a);
auto c = std::chrono::system_clock::from_time_t(b);
}
The C++ standard library doesn't yet have an API for dates as good as <chrono>
is for time. You can use the Boost date library or you can fall back on the C date library:
#include <ctime>
#include <chrono>
#include <iostream>
int main() {
std::tm epoch_start = {};
epoch_start.tm_sec = 0;
epoch_start.tm_min = 0;
epoch_start.tm_hour = 0;
epoch_start.tm_mday = 1;
epoch_start.tm_mon = 0;
epoch_start.tm_year = 70;
epoch_start.tm_wday = 4;
epoch_start.tm_yday = 0;
epoch_start.tm_isdst = -1;
std::time_t base = std::mktime(&epoch_start);
auto diff = std::chrono::system_clock::now() - std::chrono::system_clock::from_time_t(base);
std::chrono::seconds s = std::chrono::duration_cast<std::chrono::seconds>(diff);
std::cout << s.count() << '\n';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With