Cocos 里获取系统时间(年、月、日、时、分、秒、毫秒)
因为游戏要实现这个功能所以上网搜了一下,发现里面东西都并不完整,或是有BUG,就想把自己实验过的有效的方法贴出来。
//先贴一下我cpp和.h的头文件
#include "BattleField.h"
#include "cocostudio/CocoStudio.h"
#include "ui/CocosGUI.h"
#include <iostream>
#include "string"
USING_NS_CC;
using namespace cocostudio::timeline;
#include "cocos2d.h"
#include "Root.h"
#include "MapBlock.h"
USING_NS_CC;
//在 .h 的class上面写一个结构体。
typedef struct
{
int year; //年
int month; //月
int day; //日
int hour; //小时
int min; //分钟
int sec; //秒
long mil; //毫秒
}GameSystemTime; //结构体
//在头文件声明一个函数读取时间
//获取当前时间
GameSystemTime GetSystemTime();
//在cpp定义它
GameSystemTime BattleField::GetSystemTime()
{
struct timeval now;
gettimeofday(&now, nullptr);
GameSystemTime m_time;
struct tm * tm;
time_t timep;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
time(&timep);
#else
struct timeval tv;
gettimeofday(&tv, NULL);
timep = tv.tv_sec;
#endif
tm = localtime(&timep);
int year = tm->tm_year + 1900;
int month = tm->tm_mon + 1;
int day = tm->tm_mday;
int hour = tm->tm_hour;
int minute = tm->tm_min;
int second = tm->tm_sec;
struct timeval tv;
gettimeofday(&tv, NULL);
long mil = tv.tv_sec * 1000 + tv.tv_usec / 1000;
m_time.year = year;
m_time.month = month;
m_time.day = day;
m_time.hour = hour;
m_time.min = minute;
m_time.sec = second;
m_time.mil = mil;
return m_time;
}