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 ""; // 增加默认返回值,避免无返回值的情况
}

代码说明:

  1. 跨平台处理:通过 CC_TARGET_PLATFORM 宏来区分不同的平台,针对 Android 和 iOS 平台以及 Windows 平台分别进行处理。
  2. 时间获取
    • 在 Android 和 iOS 平台上,使用 gettimeofday 函数获取当前时间,然后使用 localtime 函数将时间转换为本地时间。
    • 在 Windows 平台上,使用 time 函数获取当前时间,同样使用 localtime 函数将时间转换为本地时间。
  3. 时间格式化:使用 sprintf 函数将时间信息格式化为字符串,最后使用 StringUtils::format 函数返回格式化后的字符串。

注意事项:

  • 代码中修正了变量名,避免使用与库函数名或结构体名相同的变量名,以提高代码的可读性和可维护性。
  • 在 Windows 平台的 time 函数调用中,需要传递 timep 的地址。
  • 增加了默认返回值,避免在不满足任何平台条件时无返回值的情况。