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(); | |
} | |
} |
This is a workaround for a bug in a very old version of Unity. You include the file in your project somewhere and then call FixTime() once on whatever DateTime objects you need to use.
Thanks, do you can help me with a way to geet the hour in Android?
I am developing a Oculus app and I need get a specific time zone, I created a way inscript but only run well in editor, in oculus don't run well. Thanks for attention.
I cannot use your method because I don't know hot to instance or use methods from static classes.
I'm not your C# instructor.
Nice, this was just a request if you don't want to answer is ok, thanks for your script.
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
Hi! I need to get a specific time hour in Unity for Android, this script is interesting but there are no documentation about how to use.