很多游戏具有每日登陆奖励功能,为防止玩家修改本地时间,需要读取服务器时间。
如果没有能力自己搭建服务器可以使用网络上已有的资源:
国家授时中心地址:http://www.time.ac.cn/timeflash.asp?user=flash
北京时间地址:http://www.beijing-time.org/time.asp
下面分两部分介绍获取网络时间的两种方法,第一部分解析xml,第二部分截取string.
第一部分:
通过国家授时中心链接获得的数据如下:
<?xml version="1.0" encoding="GB2312" ?> - <ntsc> - <time> <year>2011</year> <month>7</month> <day>10</day> <Weekday /> <hour>19</hour> <minite>45</minite> <second>37</second> <Millisecond /> </time> </ntsc>`然后解析xml获得当前时间,完整代码如下:
using UnityEngine; using System.Collections; using System.Xml; /// <summary> /// Get web time and parse xml /// 获取网络时间/解析xml /// </summary> public class Test1 : MonoBehaviour { public string timeURL = "http://www.time.ac.cn/timeflash.asp?user=flash";//授时中心地址 // Use this for initialization void Start() { StartCoroutine(GetTime()); } IEnumerator GetTime() { Debug.Log("Start get web time"); WWW www = new WWW(timeURL); while (!www.isDone) { Debug.Log("Getting web time"); yield return www; Debug.Log("Finish getting web time and whole xml is : " + www.text); ParseXml(www); } } public void ParseXml(WWW www) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(www.text); XmlElement root = xmlDoc.DocumentElement; XmlNodeList nodeList = root.SelectNodes("/ntsc/time"); foreach (XmlElement xe in nodeList) { foreach (XmlElement x1 in xe.ChildNodes) { if (x1.Name == "year") Debug.Log("Current year: " + x1.InnerText); if (x1.Name == "month") Debug.Log("Current month: " + x1.InnerText); if (x1.Name == "day") Debug.Log("Current day: " + x1.InnerText); if (x1.Name == "hour") Debug.Log("Current hour: " + x1.InnerText); if (x1.Name == "minite") Debug.Log("Current minite: " + x1.InnerText); if (x1.Name == "second") Debug.Log("Current second: " + x1.InnerText); } } } }获得的网络时间如下:
第二部分:
通过北京时间链接地址获得的数据如下:
t0=new Date().getTime(); nyear=2013; nmonth=6; nday=3; nwday=1; nhrs=16; nmin=57; nsec=29;
然后截取string获得网络时间,具体方法是截取";"获得年月日...然后截取"="获得对应的时间.
完整代码如下:
using UnityEngine; using System.Collections; /// <summary> /// Get web time and split string /// 获取网络时间/截取string /// </summary> public class Test2 : MonoBehaviour { public string timeURL = "http://www.beijing-time.org/time.asp";//北京时间地址 // Use this for initialization void Start() { StartCoroutine(GetTime()); } IEnumerator GetTime() { Debug.Log("Start get web time"); WWW www = new WWW(timeURL); while (!www.isDone) { Debug.Log("Getting web time"); yield return www; Debug.Log("Finish getting web time and whole xml is : " + www.text); SplitString(www); } } public void SplitString(WWW www) { string[] timeData = www.text.Split(';'); for (int i = 0; i < timeData.Length; i++) { string[] exactTime = timeData[i].Split('='); foreach (string temp in exactTime) Debug.Log(temp); } } }获得的网络时间如下:
如有任何建议请发邮件至hiramtan@qq.com