Convert long int to const time_t

Nejc Galof picture Nejc Galof · Apr 12, 2016 · Viewed 21.4k times · Source

I have variable tmit: long tmit;. I got error in this code:

printf("Time: %s",ctime(&tmit));

And error say: Cannot convert 'long int*' to 'const time_t* {aka const long long int*}' for argument '1' to 'char* ctime(const time_t*)' My question is, how convert long to time_t without lossing any information about time or how change this code, if I like to see date. I working on this answer, but I got error.

Answer

Baum mit Augen picture Baum mit Augen · Apr 12, 2016

In general, you can't as there need not be any reasonable connection between std::time_t and an integer like long.

On your specific system, std::time_t is a long long, so you can just do

std::time_t temp = tmit;

and then use temp's address. Note that this need not be portable across compilers or compiler versions (though I would not expect the latter to break).

It is worth checking whether whatever is saved in tmit gets interpreted by functions like ctime in a sensible way, as you did not tell us where that came from.

Depending on how this tmit is produced, it might also be a good idea to use an std::time_t tmit instead of long tmit from the get go and thus eliminate this conversion question entirely.

If you don't have to use the old C-style time facilities, check out the C++11 <chrono> header.