DeviceTimeZone.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. using GUPS.Obfuscator.Attribute;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Runtime.InteropServices;
  5. using UnityEngine;
  6. [DoNotObfuscateClass]
  7. [DoNotObfuscateMethodBody]
  8. public static class DeviceTimeZone
  9. {
  10. #if UNITY_IOS && !UNITY_EDITOR
  11. [DllImport("__Internal")]
  12. private static extern IntPtr IOS_GetLocalTimeZoneId();
  13. [DllImport("__Internal")]
  14. private static extern void IOS_FreeCString(IntPtr pointer);
  15. #endif
  16. /// <summary>
  17. /// 尽可能返回 IANA 时区 ID,例如 Asia/Shanghai。
  18. /// 获取失败时返回 UTC+08:00 形式。
  19. /// </summary>
  20. public static string GetIanaId()
  21. {
  22. string id;
  23. #if UNITY_ANDROID && !UNITY_EDITOR
  24. id = GetAndroidTimeZoneId();
  25. #elif UNITY_IOS && !UNITY_EDITOR
  26. id = GetIOSTimeZoneId();
  27. #else
  28. id = TimeZoneInfo.Local.Id;
  29. #endif
  30. if (string.IsNullOrEmpty(id) ||
  31. string.Equals(id, "Local", StringComparison.OrdinalIgnoreCase))
  32. {
  33. return GetUtcOffsetText();
  34. }
  35. return id;
  36. }
  37. /// <summary>
  38. /// 获取当前时区相对 UTC 的分钟差。
  39. /// 中国时区返回 480。
  40. /// </summary>
  41. public static int GetUtcOffsetMinutes()
  42. {
  43. return (int)DateTimeOffset.Now.Offset.TotalMinutes;
  44. }
  45. #if UNITY_ANDROID && !UNITY_EDITOR
  46. private static string GetAndroidTimeZoneId()
  47. {
  48. try
  49. {
  50. using (var timeZoneClass =
  51. new AndroidJavaClass("java.util.TimeZone"))
  52. using (var timeZone =
  53. timeZoneClass.CallStatic<AndroidJavaObject>("getDefault"))
  54. {
  55. return timeZone.Call<string>("getID");
  56. }
  57. }
  58. catch (Exception exception)
  59. {
  60. Debug.LogException(exception);
  61. return null;
  62. }
  63. }
  64. #endif
  65. #if UNITY_IOS && !UNITY_EDITOR
  66. private static string GetIOSTimeZoneId()
  67. {
  68. IntPtr pointer = IOS_GetLocalTimeZoneId();
  69. if (pointer == IntPtr.Zero)
  70. return null;
  71. try
  72. {
  73. return Marshal.PtrToStringAnsi(pointer);
  74. }
  75. finally
  76. {
  77. IOS_FreeCString(pointer);
  78. }
  79. }
  80. #endif
  81. private static string GetUtcOffsetText()
  82. {
  83. TimeSpan offset = DateTimeOffset.Now.Offset;
  84. string sign = offset < TimeSpan.Zero ? "-" : "+";
  85. offset = offset.Duration();
  86. return string.Format(
  87. "UTC{0}{1:00}:{2:00}",
  88. sign,
  89. offset.Hours,
  90. offset.Minutes
  91. );
  92. }
  93. }