Cross Platform way to get the time of day?

断了今生、忘了曾经 提交于 2019-12-10 18:29:40

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/11094610/cross-platform-way-to-get-the-time-of-day

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!