Reputation: 1053
How can i get count of days since epoch in C++, i know that i should use mktime
function, but i cant understand how to implement it
Thanks!
Upvotes: 2
Views: 7906
Reputation: 88235
Dates aren't easy to work with correctly. The standard library as it stands today doesn't offer the capability to do this correctly. You should use a proper date library, such as boost::date or Howard Hinnant's <date>
.
With Hinnant's library the code might look something like this:
date epoch = year(1970)/jan/day(1); // Assuming you're referring to the traditional Unix epoch (some systems such as Cocoa on OS X use the first day of the millenium, Jan 1, 2001 as their epoch)
days d = date::today() - epoch;
Upvotes: 3
Reputation: 76523
Begin by getting the current time, with time(NULL)
. Pass that value to gmtime
, which gives you back a tm*
. Read the documentation for tm
.
Upvotes: 1
Reputation: 76264
Modifying some sample code from cplusplus.com:
#include <stdio.h>
#include <time.h>
int main ()
{
time_t seconds;
seconds = time (NULL);
int daysSinceEpoch = seconds/(60*60*24);
printf ("%ld days since January 1, 1970", daysSinceEpoch);
return 0;
}
Upvotes: 4