Get current unix timestamp

I want to get the unix timestamp of the beginning of the current (or any given) hour in c / C ++.

I have it:

     time_t get_current_hour () {
         time_t beginning_of_hour;
         struct tm * ptm;

         time (& beginning_of_hour);

         ptm = gmtime (& beginning_of_hour);
         ptm-> tm_min = 0;
         ptm-> tm_sec = 0;
         ptm-> tm_zone = (char *) "GMT";

         beginning_of_hour = mktime (ptm);

         return beginning_of_hour;
     }

Which works, but with a heavy load, many of the results are not the beginning of the current hour, but the actual time.

Is there a better way to solve the problem? Why does the function return the current time?

Kindly inform Akos

+4
source share
3 answers

Perhaps you have a multi-threaded application, and gmtime calls gmtime not thread safe (repeat). If so, try using the re-version: gmtime_r

+1
source

You can do all this with time_t without having to parse it and without rebuilding it.
Just round it to a multiple of 3600:

 time_t get_current_hour(void) { time_t now; time(&now); return now - (now % 3600); } 

It might be nice to treat time_t as an integer. But I think that from the era it is guaranteed to be seconds, so everything should be fine.

+6
source

Is your application random multithreaded? gmtime returns a pointer to static memory that will be overwritten the next time the function is called. Such functions are not thread safe (and this is the only thing I can think of that will take into account your symptoms). Unix also has gmtime_r , which allows you to declare a local buffer and avoid the problem; Windows has _gmtime_s which (I think) is similar.

0
source

Source: https://habr.com/ru/post/1396217/


All Articles