2

I've been stuck on converting from an integer epoch time value to a local time.

I currently have the time since epoch stored in an integer variable, and I need a way to convert that to local time.

I have tried passing it into localtime but it doesn't seem to work.

I can get localtime to work if I simply call

  time_t rawtime;
  struct tm * timeinfo;

  time ( &rawtime );
  timeinfo = localtime ( &rawtime );

And get the rawtime directly, but I'm stuck if I want to give localtime() an integer value instead of just the current time.

Clown Baby
  • 23
  • 1
  • 1
  • 3
  • I don't really understand your question. [localtime wants a pointer parameter](http://linux.die.net/man/3/localtime), so you can't just give it some integer value. On the other hand, as [time_t in many cases is actually an integer](http://stackoverflow.com/questions/471248/what-is-ultimately-a-time-t-typedef-to), you can do `localtime ( (time_t *) &someintegervariable );`. Mind you, the latter is not guaranteed to work by the standard, it just happens to be implemented that way on most systems. Is that what you want to achieve? – fvu Feb 04 '13 at 00:51

1 Answers1

8

The localtime() function takes a pointer to const time_t so you have to first convert your integer epoch value to a time_t before calling localtime.

int epoch_time = SOME_VALUE;
struct tm * timeinfo;

/* Conversion to time_t as localtime() expects a time_t* */
time_t epoch_time_as_time_t = epoch_time;

/* Call to localtime() now operates on time_t */
timeinfo = localtime(&epoch_time_as_time_t);
Austin Phillips
  • 15,228
  • 2
  • 51
  • 50
  • 1
    Declaring variables that end with `_s` and `_t` is a bad programming practice. – MCCCS Jun 29 '18 at 17:13
  • @MCCCS maybe, but it obviates the code sample which is arguably more valuable. If someone copies this and wants to keep an unnecessarily long and cumbersome variable name, then that's up to them (IMO) and not something that detracts from Austin Phillips's answer. – kayleeFrye_onDeck Jan 29 '19 at 00:56