Skip to content

Instantly share code, notes, and snippets.

@capnmidnight
Created February 26, 2018 21:57
Show Gist options
  • 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

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