在寫每日簽到的時候,我居然使用的是本地時間...被項目經理笑哭了。。。。, 如果你在寫單機遊戲,沒有遊戲服務器,但又不想使用本地時間,就可以採用下面方法.
方法總結:
1. 使用HTTP請求獲取服務器時間,不能實時獲取服務器時間這樣高頻率的
2. 使用socket可以實時獲取服務器時間
3. 使用C#自帶API獲取sql server 標準北京時間(=。=還沒有找到這個API)
第HTTP方式:
代碼:
using UnityEngine;
using System.Collections;
using System.Timers;
using System;
using System.Text.RegularExpressions;
public class Test : MonoBehaviour {
private string url = "http://www.beijing-time.org/time.asp"; //免費獲取背景時間的Wbe 接口
private string time = string.Empty;
void OnGUI()
{
if(GUI.Button(new Rect(0,0,100,100),"獲取北京時間"))
{
StartCoroutine(GetTime());
}
GUI.Label(new Rect(0, 100, 300, 300), "時間:" + time);
}
IEnumerator GetTime()
{
Debug.Log("開始請求服務器");
WWW www = new WWW(url);
yield return www; //在這裏阻塞,等待響應之後返回
if (www.isDone && string.IsNullOrEmpty(www.error))
{
SpliitString(www);
}
}
public void SpliitString(WWW www)
{
//使用正則表達式匹配
string patten = @"[0-9]{1,};";
Regex regex = new Regex(patten);
MatchCollection result = regex.Matches(www.text);
//組織時間
time = string.Format("{0}-{1}-{2} {3}:{4}:{5}"
, result[0].Value.TrimEnd(';')
, result[1].Value.TrimEnd(';')
, result[2].Value.TrimEnd(';')
, result[4].Value.TrimEnd(';')
, result[5].Value.TrimEnd(';')
, result[6].Value.TrimEnd(';')
);
Debug.Log("北京時間:" + time);
}
}