最新文章
Cocos2d-x游戏开发实例详解7:对象释放时机
03-25 13:59
Cocos2d-x游戏开发实例详解6:自动释放池
03-25 13:55
Cocos2d-x游戏开发实例详解5:神奇的自动释放
03-25 13:49
Cocos2d-x游戏开发实例详解4:游戏主循环
03-25 13:44
Cocos2d-x游戏开发实例详解3:无限滚动地图
03-25 13:37
Cocos2d-x游戏开发实例详解2:开始菜单续
03-25 13:32
cocos2dx中如何获取系统时间
2015年02月06日 10:59
0 点赞
0 评论
更新于 2025-11-21 16:02
在 cocos2dx 开发中,有时需要获取系统时间。下面为大家详细分享获取系统时间的代码,希望对大家有所帮助。
以下是获取系统时间的代码实现:
std::string Tools::getcurrTime()
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
struct timeval now;
struct tm* timeInfo; // 避免使用 time 作为变量名,因为它是库函数名
gettimeofday(&now, NULL);
timeInfo = localtime(&now.tv_sec);
int year = timeInfo->tm_year + 1900;
cocos2d::log("year = %d", year);
char date[32] = {0};
sprintf(date, "%d%02d%02d", (int)timeInfo->tm_year + 1900, (int)timeInfo->tm_mon + 1, (int)timeInfo->tm_mday);
cocos2d::log("%s", date);
return cocos2d::StringUtils::format("%s", date);
#endif
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
struct tm* tmInfo; // 避免使用 tm 作为变量名,因为它是结构体名
time_t timep;
time(&timep); // 修正为传递地址
tmInfo = localtime(&timep);
char date[32] = {0};
sprintf(date, "%d-%02d-%02d", (int)tmInfo->tm_year + 1900, (int)tmInfo->tm_mon + 1, (int)tmInfo->tm_mday);
cocos2d::log("%s", date);
return cocos2d::StringUtils::format("%s", date);
#endif
return ""; // 增加默认返回值,避免无返回值的情况
}
代码说明:
- 跨平台处理:通过
CC_TARGET_PLATFORM宏来区分不同的平台,针对 Android 和 iOS 平台以及 Windows 平台分别进行处理。 - 时间获取:
- 在 Android 和 iOS 平台上,使用
gettimeofday函数获取当前时间,然后使用localtime函数将时间转换为本地时间。 - 在 Windows 平台上,使用
time函数获取当前时间,同样使用localtime函数将时间转换为本地时间。
- 在 Android 和 iOS 平台上,使用
- 时间格式化:使用
sprintf函数将时间信息格式化为字符串,最后使用StringUtils::format函数返回格式化后的字符串。
注意事项:
- 代码中修正了变量名,避免使用与库函数名或结构体名相同的变量名,以提高代码的可读性和可维护性。
- 在 Windows 平台的
time函数调用中,需要传递timep的地址。 - 增加了默认返回值,避免在不满足任何平台条件时无返回值的情况。