i need to change the string of numbers returned by time() (in a time_t type variable) into a string type varaible. what is the best way to do this?
Printable View
i need to change the string of numbers returned by time() (in a time_t type variable) into a string type varaible. what is the best way to do this?
ctime() or strftime() via localtime() or gmtime() if you need more control.
http://cppreference.com/stddate.html
more detail on the above functions
strftime() is a better choice than ctime() or asctime() simply because ctime() and asctime() return a pointer to a local static buffer that will be overwritten during each subquent call. Of course if you are only dealing with one date then thats perfectly fine ;)
i don't think you understood what i meant. time returns time_t which contains the number of seconds since 1/1/1970 i need to convert that number into a string (just the same thing, but i need it as a string type). sorry for late reply
sprintf() is the easist way :)
Where buffer of course is an array of characters.Code:sprintf(buffer, "%u", (unsigned) time(NULL));
Such an operation is inherently nonportable. time_t is an arithmetic type, but the only operation defined for it is a comparison to (time_t)-1. So any integer-string conversions would be relying on a specific representation of time_t. However, because most implementations use unsigned long or similar, sprintf should work.Quote:
Originally Posted by whackaxe
Code:time_t present = time(0);
sprintf(buffer, "%lu", (unsigned long)present);