在C++中获取当前时间并转换为可读时间格式(Win32和Linux通用)

所谓的跨平台是因为使用了不同的API, 用宏定义区别Windows和Unix. 

方法如下:

#ifdef WIN32 #define LOCALTIME_R(t) localtime((t)) #else #define LOCALTIME_R(t) localtime_r((t), (struct tm *)&tmres) #endif
如此定义之后, 只需要如下代码即可:

#include <stdio.h> #include <stdio.h> #include <time.h> main() { struct tm *tmNow; time_t long_time; time(&long_time ); /* Get time as long integer. */ tmNow = LOCALTIME_R( &long_time ); /* Convert to local time. */ printf("%d年%d月%d日 %d时%d分%d秒",tmNow->tm_year, tmNow->tm_mon + 1, tmNow->tm_mday, tmNow->tm_hour, tmNow->tm_min, tmNow->tm_sec); return; } 

如此即可在windows或Linux下跨平台使用该段代码.

 

参考: http://topic.csdn.net/t/20031118/17/2468854.html

你可能感兴趣的:(C++,linux,windows,struct,api,跨平台)