scottc5
scottc5

Reputation: 51

Please help me with a simple c++ std::time_t question

I am trying to get the current time and subtract a set amount of seconds to find a time in the past. See my code example below...

#include <ctime>
#include <stdio.h>
void main()
{
   uint32_t sec = 100;
   std::time_t t = std::time(NULL);
   std::time_t mt  = t - (std::time_t)sec;
   struct std::tm* currTime = std::localtime( &t);
   printf( "Current Time  %s\n", asctime(currTime) );
   struct std::tm* modTime = std::localtime( &mt);
   printf( "Modified Time %s\n", asctime(modTime) );
   printf( "Current Time  %s\n", asctime(currTime) );
}

Initially it seems like it works with the first two prints, but the third print is the same as the second print. What am I doing wrong? Thanks!

Output:

Current Time  Thu Oct 29 18:10:39 2020

Modified Time Thu Oct 29 18:08:59 2020

Current Time  Thu Oct 29 18:08:59 2020

Upvotes: 1

Views: 304

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118340

This is explained in the manual page for localtime(3):

The return value points to a statically allocated struct which might be overwritten by subsequent calls to any of the date and time functions.

Your localtime always returns a pointer to the same internal object, and each time it gets called it overwrites its contents and returns the same pointer.

So, both of your pointers end up pointing to the same object, with the same contents.

As the manual page explains, there's an alternative localtime_r library call that does not suffer this limitation, but you have to do more work to use it.

Upvotes: 4

Related Questions