Converting from an integer epoch time value to loc

2019-04-15 02:40发布

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.

标签: c time epoch
1条回答
Anthone
2楼-- · 2019-04-15 03:19

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);
查看更多
登录 后发表回答