Skip to content

Instantly share code, notes, and snippets.

@capnmidnight
Created February 26, 2018 21:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save capnmidnight/8f36856eb93e8350e4eb06043a4216a4 to your computer and use it in GitHub Desktop.
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
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();
}
}
@JulianCanoDev
Copy link

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.

@capnmidnight
Copy link
Author

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.

@JulianCanoDev
Copy link

Thanks, do you can help me with a way to geet the hour in Android?

@JulianCanoDev
Copy link

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.

@JulianCanoDev
Copy link

I cannot use your method because I don't know hot to instance or use methods from static classes.

@capnmidnight
Copy link
Author

I'm not your C# instructor.

@JulianCanoDev
Copy link

JulianCanoDev commented Mar 25, 2022

Nice, this was just a request if you don't want to answer is ok, thanks for your script.

@JulianCanoDev
Copy link

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