jmasterx jmasterx - 10 months ago 69
C Question

Cross Platform way to get the time of day?

Is there a simple way to get time time of day (17:30, 01:20...etc) that would work on iOS, OSX, Linux and Windows?

If not is there a Windows way and a posix way or something?


Answer Source

You can retrieve the time with time_t now = time(NULL); or time(&now);

You then usually convert to local time with struct tm *tm_now = localtime(&now);. A struct tm contains fields for the year, month, day, day of week, hour, minute, and second. If you want to produce printable output, strftime supports that directly.

Both of these are in the C and C++ standards, so they are available on most normal platforms.

If you really only care about C++, you can use std::put_time, which is similar to strftime, but a little bit simpler to use for the typical case of writing the output to a stream.