62 lines
1.7 KiB
C#
62 lines
1.7 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Globalization;
|
|
using UnityEngine;
|
|
using UnityEngine.Networking;
|
|
|
|
public class InternetTime : MonoBehaviour
|
|
{
|
|
public static InternetTime Ins;
|
|
private void Awake() { Ins = this; DontDestroyOnLoad(gameObject); }
|
|
|
|
public DateTime Time { get; private set; }
|
|
|
|
// 한국 표준시 = UTC+9
|
|
private static readonly TimeSpan KSTOffset = TimeSpan.FromHours(9);
|
|
|
|
public void Start()
|
|
{
|
|
StartCoroutine(GetKSTTime());
|
|
}
|
|
|
|
IEnumerator Co_1Sec()
|
|
{
|
|
while (true)
|
|
{
|
|
yield return new WaitForSeconds(1f);
|
|
Time = Time.AddSeconds(1f);
|
|
}
|
|
}
|
|
|
|
IEnumerator GetKSTTime()
|
|
{
|
|
Time = DateTime.Now;
|
|
using (UnityWebRequest req = UnityWebRequest.Get("https://google.com"))
|
|
{
|
|
yield return req.SendWebRequest();
|
|
if (req.result == UnityWebRequest.Result.ConnectionError ||
|
|
req.result == UnityWebRequest.Result.ProtocolError)
|
|
{
|
|
Time = DateTime.Now;
|
|
}
|
|
else
|
|
{
|
|
string dateHeader = req.GetResponseHeader("date");
|
|
if (!string.IsNullOrEmpty(dateHeader))
|
|
{
|
|
// 서버가 준 시간은 UTC 기준
|
|
DateTime utcTime = DateTime.ParseExact(
|
|
dateHeader,
|
|
"ddd, dd MMM yyyy HH:mm:ss 'GMT'",
|
|
CultureInfo.InvariantCulture.DateTimeFormat,
|
|
DateTimeStyles.AssumeUniversal
|
|
);
|
|
|
|
Time = utcTime.ToUniversalTime() + KSTOffset;
|
|
}
|
|
}
|
|
|
|
StartCoroutine(Co_1Sec());
|
|
}
|
|
}
|
|
} |