using System; using System.Globalization; using System.Net; using Cysharp.Threading.Tasks; using UniRx; public class NetTime : LazySingleton { public readonly ReactiveProperty IsAvailable = new ReactiveProperty(); public IObservable IsAvailableAsObservable() => IsAvailable; public DateTime Time => DateTime.Now + _timeDelta; private TimeSpan _timeDelta = TimeSpan.Zero; private static async UniTask GetTimeAsync() { using (var response = await WebRequest.Create("https://www.google.com").GetResponseAsync()) return DateTime.ParseExact(response.Headers["date"], "ddd, dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.AssumeUniversal); } private void Awake() { UniTask.Run(CacheTimeAsync); } private void OnApplicationFocus(bool hasFocus) { if (hasFocus == false) { IsAvailable.Value = false; return; } UniTask.Run(CacheTimeAsync); } private async void CacheTimeAsync() { try { var googleTime = await GetTimeAsync(); var deviceTime = DateTime.Now; _timeDelta = googleTime - deviceTime; IsAvailable.Value = true; } catch (Exception) { Log.Error("Can't connect with google."); } } }