using GUPS.Obfuscator.Attribute; using System; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; [DoNotObfuscateClass] [DoNotObfuscateMethodBody] public static class DeviceTimeZone { #if UNITY_IOS && !UNITY_EDITOR [DllImport("__Internal")] private static extern IntPtr IOS_GetLocalTimeZoneId(); [DllImport("__Internal")] private static extern void IOS_FreeCString(IntPtr pointer); #endif /// /// 尽可能返回 IANA 时区 ID,例如 Asia/Shanghai。 /// 获取失败时返回 UTC+08:00 形式。 /// public static string GetIanaId() { string id; #if UNITY_ANDROID && !UNITY_EDITOR id = GetAndroidTimeZoneId(); #elif UNITY_IOS && !UNITY_EDITOR id = GetIOSTimeZoneId(); #else id = TimeZoneInfo.Local.Id; #endif if (string.IsNullOrEmpty(id) || string.Equals(id, "Local", StringComparison.OrdinalIgnoreCase)) { return GetUtcOffsetText(); } return id; } /// /// 获取当前时区相对 UTC 的分钟差。 /// 中国时区返回 480。 /// public static int GetUtcOffsetMinutes() { return (int)DateTimeOffset.Now.Offset.TotalMinutes; } #if UNITY_ANDROID && !UNITY_EDITOR private static string GetAndroidTimeZoneId() { try { using (var timeZoneClass = new AndroidJavaClass("java.util.TimeZone")) using (var timeZone = timeZoneClass.CallStatic("getDefault")) { return timeZone.Call("getID"); } } catch (Exception exception) { Debug.LogException(exception); return null; } } #endif #if UNITY_IOS && !UNITY_EDITOR private static string GetIOSTimeZoneId() { IntPtr pointer = IOS_GetLocalTimeZoneId(); if (pointer == IntPtr.Zero) return null; try { return Marshal.PtrToStringAnsi(pointer); } finally { IOS_FreeCString(pointer); } } #endif private static string GetUtcOffsetText() { TimeSpan offset = DateTimeOffset.Now.Offset; string sign = offset < TimeSpan.Zero ? "-" : "+"; offset = offset.Duration(); return string.Format( "UTC{0}{1:00}:{2:00}", sign, offset.Hours, offset.Minutes ); } }