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?
Thanks
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?
Thanks
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.
with C++11 you can use
#include <iostream>
#include <iomanip>
#include <ctime>
int main()
{
std::time_t t = std::time(nullptr);
std::cout << "UTC: " << std::put_time(std::gmtime(&t), "%c %Z") << '\n'
<< "local: " << std::put_time(std::localtime(&t), "%c %Z") << '\n';
}
which should produce on (any platform)
UTC: Wed Dec 28 11:47:03 2011 GMT
local: Wed Dec 28 06:47:03 2011 EST
though std::put_time()
(from iomanip
) is not yet implemented in, say, gcc 4.7.0.