DeviceTimeZone.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #if UNITY_EDITOR
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Runtime.InteropServices;
  5. using UnityEngine;
  6. public static class DeviceTimeZone
  7. {
  8. #if UNITY_IOS && !UNITY_EDITOR
  9. private static IntPtr IOS_GetLocalTimeZoneId() => NativeApi.TimeZone.IOS_GetLocalTimeZoneId();
  10. private static void IOS_FreeCString(IntPtr pointer) => NativeApi.TimeZone.IOS_FreeCString(pointer);
  11. #endif
  12. public static string GetIanaId()
  13. {
  14. string id;
  15. #if UNITY_ANDROID && !UNITY_EDITOR
  16. id = GetAndroidTimeZoneId();
  17. #elif UNITY_IOS && !UNITY_EDITOR
  18. id = GetIOSTimeZoneId();
  19. #else
  20. id = TimeZoneInfo.Local.Id;
  21. #endif
  22. if (string.IsNullOrEmpty(id) ||
  23. string.Equals(id, "Local", StringComparison.OrdinalIgnoreCase))
  24. {
  25. return GetUtcOffsetText();
  26. }
  27. return id;
  28. }
  29. public static int GetUtcOffsetMinutes()
  30. {
  31. return (int)DateTimeOffset.Now.Offset.TotalMinutes;
  32. }
  33. #if UNITY_ANDROID && !UNITY_EDITOR
  34. private static string GetAndroidTimeZoneId()
  35. {
  36. try
  37. {
  38. using (var timeZoneClass =
  39. new AndroidJavaClass("java.util.TimeZone"))
  40. using (var timeZone =
  41. timeZoneClass.CallStatic<AndroidJavaObject>("getDefault"))
  42. {
  43. return timeZone.Call<string>("getID");
  44. }
  45. }
  46. catch (Exception exception)
  47. {
  48. Debug.LogException(exception);
  49. return null;
  50. }
  51. }
  52. #endif
  53. #if UNITY_IOS && !UNITY_EDITOR
  54. private static string GetIOSTimeZoneId()
  55. {
  56. IntPtr pointer = IOS_GetLocalTimeZoneId();
  57. if (pointer == IntPtr.Zero)
  58. return null;
  59. try
  60. {
  61. return Marshal.PtrToStringAnsi(pointer);
  62. }
  63. finally
  64. {
  65. IOS_FreeCString(pointer);
  66. }
  67. }
  68. #endif
  69. private static string GetUtcOffsetText()
  70. {
  71. TimeSpan offset = DateTimeOffset.Now.Offset;
  72. string sign = offset < TimeSpan.Zero ? "-" : "+";
  73. offset = offset.Duration();
  74. return string.Format(
  75. "UTC{0}{1:00}:{2:00}",
  76. sign,
  77. offset.Hours,
  78. offset.Minutes
  79. );
  80. }
  81. }
  82. #endif