Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert long int to const time_t

Tags:

c++

ctime

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.

like image 476
Nejc Galof Avatar asked Apr 12 '16 14:04

Nejc Galof


People also ask

Is time_t a long int?

The variable time_t is a 32-bit long int that can hold values up to 2147483647 before it overflows.

What is time_t C++?

The time_t type is an arithmetic type that represents a date and time. The actual type and the encoding of the date and time are implementation-defined.

What is the format of ctime?

Description. The ctime() function converts the time value pointed to by time to local time in the form of a character string. A time value is usually obtained by a call to the time() function. The ctime() function uses a 24-hour clock format.


2 Answers

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.

like image 81
Baum mit Augen Avatar answered Sep 18 '22 16:09

Baum mit Augen


You cannot simply "convert" one type of pointer to a pointer to an incompatible object type.

What you want to do, is to create an object of that another type, then initialize it using the impicit conversion between the object types, and finally pass a pointer to the newly created object:

std::time_t t = tmit;
ctime(&t);
like image 42
eerorika Avatar answered Sep 21 '22 16:09

eerorika