Unity3D如何獲取時間戳或北京時間
阿新 • • 發佈:2020-05-25
本文例項為大家分享了Unity3D獲取時間戳或北京時間的具體程式碼,供大家參考,具體內容如下
單機遊戲因為沒有伺服器下發時間戳所以要自己獲取,當然也可以用現成的時間API來獲取。
如果獲取本地時間,會導致玩家隨意修改日期來達到資料更改,如每日獎品、每日獎勵等等。
單機遊戲本來就不要網路的,可是獲取時間需要網路,這有點矛盾,有沒有誰有更好的解決方案呢?
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine( GetBeiJingTime()); Console.ReadKey(); } public static string GetBeiJingTime() { bool isget = false; string result = string.Empty; try { HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://open.baidu.com/special/time/");//百度北京時間地址 req.Headers.Add("content","text/html; charset=gbk"); HttpWebResponse res = (HttpWebResponse)req.GetResponse(); Stream stream = res.GetResponseStream(); StreamReader sr = new StreamReader(stream,Encoding.GetEncoding("gbk")); string html = sr.ReadToEnd(); Func<string,string> f1 = (p) =>{ Regex reg = new Regex("(?<=baidu_time\\().*?(?=\\))"); return reg.Matches(p)[0].Value;}; string time = f1(html).Substring(0,10);//這裡是時間戳 stream.Dispose(); sr.Dispose(); DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970,1,1)); long lTime = long.Parse(time + "0000000"); TimeSpan toNow = new TimeSpan(lTime); result = dtStart.Add(toNow).ToString("yyyyMMdd"); isget = true; } catch (Exception) { } finally { if (!isget)result = "19700101";//如果沒有網路就返回預設 } return result; } } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。