cocos获取网络时间和系统时间(完美)

本文介绍了在cocos2d-x中如何获取网络时间以及系统时间。通过CCHttpClient异步请求百度的时间API,利用rapidjson解析JSON数据,若解析失败则采用正则表达式提取时间。当网络请求失败或解析失败时,会尝试获取本地系统时间。同时,文章强调了在CCHttpClient异步请求中正确处理回调的方法,确保在数据准备好后再进行使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

访问百度的时间api获取到网页,使用CCHttpClient进行网络时间的数据请求和使用rapidjson解析Http请求得到的json数据 
如果使用rapidjson解析失败则对网络数据的字符串使用正则进行截取,获取时间字符串的10个字符,atoi得到时间值;
如果使用rapidjson解析失败则对网络数据的字符串使用正则(c++11 <regex>)进行截取,获取时间字符串的10个字符,
atoi得到时间值;如果网络访问失败或者获取解析网络数据失败,则根据不同平台去获取本地时间

新建一个c++类MyTime,继承自CCNode并重写init()方法。然后引入CCHttpClientrapidjson需要的头文件

#ifndef __MYTIME_H__
#define __MYTIME_H__

#include "cocos2d.h"
#include "cocos-ext.h"
#include "json\rapidjson.h"
#include "network\HttpClient.h"

using namespace std;
using namespace cocos2d;
using namespace extension;
using namespace rapidjson;
using namespace network;

//class MyTime;
//typedef void (Object::*SEL_MyTime)(MyTime* pSender);
//#define myTime_selector(_SELECTOR)(SEL_MyTime)(&_SELCTOR);

class MyTime : public Node
{
	public :

	CREATE_FUNC(MyTime);

	CC_SYNTHESIZE(int, m_Year, Year);
	CC_SYNTHESIZE(int, m_Month, Month);
	CC_SYNTHESIZE(int, m_Day, Day);
	CC_SYNTHESIZE(int, m_Hour, Hour);
	CC_SYNTHESIZE(int, m_Minute, Minute);
	CC_SYNTHESIZE(int, m_Second, Second);
	
	
	void requestNetTime();
	void requestNetTime(/*CCObject* pTarget, */const function<void()>& pSelector);
	//void displayTime();

private:
	virtual bool init();

	function<void()> m_pSelector;
	//SEL_MyTime m_pSelector;

	void onHttpComplete(HttpClient* sender, HttpResponse* response);

	//解析json文件,获取时间值
	bool readJson(string jsonStr);

	//从doucment对象获取key值失败,进行的截取字符串操作,获取时间值
	bool splitString(const string content,string pattern);

	//网络获取时间值失败,进行本地获取时间值,
	void getLocalTime();

	//设置时间对象
	void setTime(time_t tm);
};

#endif</span></span>

<think>我们正在使用CocosCreator3.x版本,因此不能使用全局变量`cc`。获取当前系统时间的方法与在JavaScript中一致,使用`Date`对象即可。但是需要注意,CocosCreator3.x使用的是TypeScript,所以我们可以直接使用ES6的Date对象。步骤:1.创建一个新的Date对象。2.使用Date对象的方法获取具体的时间信息(年、月、日、时、分、秒、毫秒等)。示例代码:在CocosCreator3.x的脚本中:```typescriptimport{_decorator,Component}from'cc';const{ccclass}=_decorator;@ccclass('TimeDisplay')exportclassTimeDisplayextendsComponent{update(){//每帧获取当前时间letnow=newDate();//获取时间信息letyear=now.getFullYear();letmonth=now.getMonth()+1;//月份从0开始,需要+1letdate=now.getDate();lethours=now.getHours();letminutes=now.getMinutes();letseconds=now.getSeconds();letmilliseconds=now.getMilliseconds();//格式化为字符串lettimeString=`${year}-${month}-${date}${hours}:${minutes}:${seconds}.${milliseconds}`;console.log('当前时间:',timeString);}}```注意:`Date`对象是JavaScript内置的,不需要从'cc'模块导入。如果需要在界面上显示时间,可以将时间字符串赋值给一个Label组件。另外,引用[2]中提供了Date对象的各种方法,我们可以根据需求选择使用。关于引用[3]引用[4],它们主要介绍了CocosCreator的一些背景开发环境配置,与本问题关系不大,但我们可以知道CocosCreator是一个可视化编辑的引擎,我们可以将获取时间显示在UI上。因此,在CocosCreator中获取当前系统时间的方法就是使用JavaScript(TypeScript)的Date对象。下面是一个在UI上显示时间的示例:1.创建一个空节点,挂载上面的脚本(例如TimeDisplay)。2.在场景中创建一个Label节点,并将这个Label节点赋值给脚本中的属性。3.在脚本中更新Label的字符串。修改后的脚本:```typescriptimport{_decorator,Component,Label}from'cc';const{ccclass,property}=_decorator;@ccclass('TimeDisplay')exportclassTimeDisplayextendsComponent{@property(Label)timeLabel:Label|null=null;//关联一个Label组件update(){letnow=newDate();letyear=now.getFullYear();letmonth=now.getMonth()+1;letdate=now.getDate();lethours=now.getHours().toString().padStart(2,'0');//补零letminutes=now.getMinutes().toString().padStart(2,'0');letseconds=now.getSeconds().toString().padStart(2,'0');//格式化lettimeString=`${year}-${month}-${date}${hours}:${minutes}:${seconds}`;if(this.timeLabel){this.timeLabel.string=timeString;}}}```这样,每帧都会更新时间显示。注意:如果不需要每帧更新,可以使用定时器(setInterval)来每秒更新一次,以减少性能消耗。每秒更新一次的版本:```typescriptimport{_decorator,Component,Label}from'cc';const{ccclass,property}=_decorator;@ccclass('TimeDisplay')exportclassTimeDisplayextendsComponent{@property(Label)timeLabel:Label|null=null;onLoad(){//每秒更新一次this.schedule(this.updateTime,1);}updateTime(){letnow=newDate();letyear=now.getFullYear();letmonth=now.getMonth()+1;letdate=now.getDate();lethours=now.getHours().toString().padStart(2,'0');letminutes=now.getMinutes().toString().padStart(2,'0');letseconds=now.getSeconds().toString().padStart(2,'0');lettimeString=`${year}-${month}-${date}${hours}:${minutes}:${seconds}`;if(this.timeLabel){this.timeLabel.string=timeString;}}}```这样每秒更新一次,更加高效。总结:在CocosCreator中获取当前系统时间,直接使用JavaScript的Date对象即可,不需要依赖引擎的API。引用说明:关于Date对象的使用方法,可以参考引用[2]中提供的方法列表,但注意我们是在TypeScript中使用,方法相同。引用标识:[^2]注意:在CocosCreator3.x中,我们使用TypeScript,因此代码需要符合TypeScript的语法。相关问题:1.如何在CocosCreator中格式化日期时间?2.如何将时间显示为倒计时格式?3.CocosCreator中如何实现一个实时更新的时钟?4.如何获取网络时间而不是本地时间?</think>### Cocos Creator 中获取当前系统时间的方法 在 Cocos Creator 中获取当前系统时间,可以直接使用 JavaScript 的 `Date` 对象,无需依赖引擎 API。以下是完整实现方法: #### 基本时间获取 ```typescript // 创建 Date 对象获取当前时间 const now = new Date(); // 获取时间各组成部分 const year = now.getFullYear(); // 四位年份 (2023) const month = now.getMonth() + 1; // 月份 (0-11, 需要+1) const day = now.getDate(); // 日期 (1-31) const hours = now.getHours(); // 小时 (0-23) const minutes = now.getMinutes(); // 分钟 (0-59) const seconds = now.getSeconds(); // 秒数 (0-59) const milliseconds = now.getMilliseconds(); // 毫秒 (0-999) // 获取星期 (0-6, 0=星期日) const weekday = now.getDay(); // 时间戳(毫秒数) const timestamp = now.getTime(); ``` #### 格式化时间输出 ```typescript // 格式化为 YYYY-MM-DD HH:mm:ss function formatTime(date: Date): string { const pad = (n: number) => n.toString().padStart(2, '0'); return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())} ` + `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`; } // 使用示例 const currentTime = formatTime(new Date()); console.log("当前时间:", currentTime); // 输出: 2023-08-15 14:30:45 ``` #### 在组件中实时更新时间显示 ```typescript import { _decorator, Component, Label } from 'cc'; const { ccclass, property } = _decorator; @ccclass('TimeDisplay') export class TimeDisplay extends Component { @property(Label) timeLabel: Label | null = null; // 关联UI中的Label组件 start() { // 每秒更新一次时间 this.schedule(() => { if (this.timeLabel) { this.timeLabel.string = formatTime(new Date()); } }, 1); } } ``` #### 本地化时间显示 ```typescript // 获取本地化日期字符串 const localDateString = new Date().toLocaleDateString(); // 示例输出: "2023/8/15" // 获取本地化时间字符串 const localTimeString = new Date().toLocaleTimeString(); // 示例输出: "下午2:30:45" // 获取完整本地化字符串 const fullLocalString = new Date().toLocaleString(); // 示例输出: "2023/8/15 下午2:30:45" ``` #### 注意事项 1. **时区处理** `Date` 对象默认使用用户本地时区,如需 UTC 时间: ```typescript const utcHours = now.getUTCHours(); ``` 2. **性能优化** 避免在 `update()` 中频繁创建 `Date` 对象,建议: ```typescript private lastUpdate = 0; update(deltaTime: number) { this.lastUpdate += deltaTime; if(this.lastUpdate > 1) { // 每秒更新 this.updateTimeDisplay(); this.lastUpdate = 0; } } ``` 3. **时间精度** 对于高精度需求(如游戏计时),建议使用 `director.getTotalTime()` 获取引擎运行时间: ```typescript import { director } from 'cc'; const preciseTime = director.getTotalTime(); // 毫秒精度 ``` > 参考:[Date 对象文档 MDN](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date)[^2] --- ### 示例效果 在场景中创建 UI Label 并挂载 `TimeDisplay` 组件后,将显示实时更新的时间: ``` 2023-08-15 14:30:45 ```
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值