Created
February 26, 2018 21:57
-
-
Save capnmidnight/8f36856eb93e8350e4eb06043a4216a4 to your computer and use it in GitHub Desktop.
Fix DateTime values in Unity on Android when building with .NET 4.6 support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class DateTimeExt | |
{ | |
#if UNITY_ANDROID && NET_4_6 && !UNITY_EDITOR | |
static int cachedOffset = 0; | |
#endif | |
static int MillisecondsOffset | |
{ | |
get | |
{ | |
#if !UNITY_ANDROID || !NET_4_6 || UNITY_EDITOR | |
return 0; | |
#else | |
if(cachedOffset == 0) | |
{ | |
var calendar = new AndroidJavaObject("java.util.GregorianCalendar"); | |
var timeZone = calendar.Call<AndroidJavaObject>("getTimeZone"); | |
cachedOffset = timeZone.Call<int>("getRawOffset"); | |
} | |
return cachedOffset; | |
#endif | |
} | |
} | |
/// <summary> | |
/// The latest versions of Unity running .NET rutime 4.6 on Android have a defect that | |
/// local times get reported as UTC and no timezone information is available. | |
/// | |
/// WARNING: do not call this function during app startup, such as initializing fields | |
/// in classes. | |
/// </summary> | |
/// <param name="utcTime"></param> | |
/// <returns></returns> | |
public static DateTime FixTime(this DateTime time) | |
{ | |
if(time.Kind == DateTimeKind.Local) | |
{ | |
return time.AddMilliseconds(MillisecondsOffset); | |
} | |
else if(time.Kind == DateTimeKind.Utc) | |
{ | |
return time.AddMilliseconds(-MillisecondsOffset); | |
} | |
else | |
{ | |
return time; | |
} | |
} | |
public static DateTime? FixTime(this DateTime? time) | |
{ | |
return time?.FixTime(); | |
} | |
} |
I found the solution, thanks for your script, variable to be used have to be static.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice, this was just a request if you don't want to answer is ok, thanks for your script.