3

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

jmasterx
  • 52,639
  • 96
  • 311
  • 557
  • You can try [this answer](http://stackoverflow.com/questions/2494356/how-to-use-gettimeofday-or-something-equivalent-with-visual-studio-c-2008), and POSIX has `gettimeofday` – jxh Jun 19 '12 at 05:01
  • 1
    If you have to cross a platform just to get the time well that's just silly. – Captain Obvlious Jun 19 '12 at 05:01

2 Answers2

9

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.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
5

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.

Community
  • 1
  • 1
Walter
  • 44,150
  • 20
  • 113
  • 196