/// <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;
}
}
DateTime.Now returns UTC Time if we build Xamarin.Android app with azure pipeline.
Shingala A
25
Reputation points
Hi, Team,
We have currently one project associated with Xamarin.Android. DateTime.Now returns UTC Time instead of returning local time only when we build Xamarin.Android app with azure pipeline. It is working fine if we create build using visual studio 2022. Our device time and time zone is also properly set. Issue is coming in android 14 devices only.
Looking forward to your response.
Thank you!
1 answer
Sort by: Most helpful
-
Cory W 10 Reputation points
2024-11-21T01:11:08.33+00:00