Вопрос

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!

Это было полезно?

Решение

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;
}

Другие советы

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;

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top