A Microsoft framework for building cross-platform mobile apps using .NET and C# with native performance and user interfaces.
/// <summary>
/// !!! REPLACES DateTime.Now - Gets the current local date and time, including the correct UTC offset from the Android time zone.
/// </summary>
/// <returns>A DateTime object representing the current local time.</returns>
public static DateTime GetCurrentDateTime()
{
// Step 1: Get the current UTC time
DateTime utcNow = DateTime.UtcNow;
try
{
// Step 2: Retrieve the Android device's default time zone
var javaTimeZone = Java.Util.TimeZone.Default;
// Step 3: Create a Java.Util.Date object using the current UTC time in milliseconds
long currentTimeMillis = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds;
var javaDate = new Java.Util.Date(currentTimeMillis);
// Step 4: Calculate the raw offset (standard time) and daylight saving adjustment
int rawOffsetMillis = javaTimeZone.RawOffset; // Base offset in milliseconds
int dstOffsetMillis = javaTimeZone.DSTSavings; // Daylight saving time adjustment in milliseconds (if applicable)
// Step 5: Determine if daylight saving is currently active
bool isDstActive = javaTimeZone.InDaylightTime(javaDate);
// Step 6: Calculate the total offset in hours
int totalOffsetMillis = rawOffsetMillis + (isDstActive ? dstOffsetMillis : 0);
TimeSpan totalOffset = TimeSpan.FromMilliseconds(totalOffsetMillis);
//System.Console.WriteLine($"Raw Offset (ms): {rawOffsetMillis}, DST Active: {isDstActive}, Total Offset: {totalOffset}");
// Step 7: Apply the offset to UTC time
return utcNow + totalOffset;
}
catch (System.Exception ex)
{
// Log and fallback to UTC in case of errors
GetLogger("Utils").Error($"Error calculating local time: {ex.Message}");
return utcNow;
}
}