Cross-platform way to get the time of day?

Is there an easy way to get the time (17:30, 01:20 ... etc.) that will work on iOS, OSX, Linux and Windows?

If there is no Windows path and posix path or something else?

thank

+3
c ++ c cross-platform
Jun 19 2018-12-12T00:
source share
2 answers

You can get the time using time_t now = time(NULL); or time(&now);

Then you usually convert to local time using struct tm *tm_now = localtime(&now); . A struct tm contains fields for year, month, day, day of the week, hour, minute and second. If you want to create print output, strftime supports this directly.

Both comply with C and C ++ standards, so they are available on most common platforms.

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

+8
Jun 19 2018-12-12T00:
source share

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'; } 

to be produced on (any platform)

UTC: Wed Dec 28 11:47:03 2011 GMT

local: Wed Dec 28 06:47:03 2011 EST

although std::put_time() (from iomanip ) is not yet implemented, say, in gcc 4.7.0.

+4
Jun 19 '12 at 8:16
source share



All Articles