From d919503c3c96f09927d06d361725ebfb1870b7eb Mon Sep 17 00:00:00 2001 From: Matthew Leibowitz Date: Fri, 22 Nov 2024 03:07:44 +0800 Subject: [PATCH] Fall back to loading .NET 8 date strings Fixes #25930 --- .../src/Preferences/Preferences.uwp.cs | 10 ++++++--- .../DeviceTests/Tests/Preferences_Tests.cs | 21 +++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/src/Essentials/src/Preferences/Preferences.uwp.cs b/src/Essentials/src/Preferences/Preferences.uwp.cs index 17baa54d4bef..979ce6912759 100644 --- a/src/Essentials/src/Preferences/Preferences.uwp.cs +++ b/src/Essentials/src/Preferences/Preferences.uwp.cs @@ -212,12 +212,16 @@ public T Get(string key, T defaultValue, string sharedName = null) { if (defaultValue is DateTime dt) { - long tempValue = (long)Convert.ChangeType(value, typeof(long), CultureInfo.InvariantCulture); - return (T)(object)DateTime.FromBinary(tempValue); + // long for the .NET 9+ format + if (long.TryParse(value, CultureInfo.InvariantCulture, out var longValue)) + return (T)(object)DateTime.FromBinary(longValue); + // DateTime string for the .NET 8 format + if (DateTime.TryParse(value, CultureInfo.InvariantCulture, out var datetimeValue)) + return (T)(object)datetimeValue; } else if (defaultValue is DateTimeOffset dto) { - if (DateTimeOffset.TryParse((string)value, out var dateTimeOffset)) + if (DateTimeOffset.TryParse((string)value, CultureInfo.InvariantCulture, out var dateTimeOffset)) { return (T)(object)dateTimeOffset; } diff --git a/src/Essentials/test/DeviceTests/Tests/Preferences_Tests.cs b/src/Essentials/test/DeviceTests/Tests/Preferences_Tests.cs index 6ad20e0f767c..bfc376f9d48f 100644 --- a/src/Essentials/test/DeviceTests/Tests/Preferences_Tests.cs +++ b/src/Essentials/test/DeviceTests/Tests/Preferences_Tests.cs @@ -246,6 +246,27 @@ public void DateTimePreservesKind(string sharedName, DateTimeKind kind) public void FailsWithUnsupportedType() => Assert.Throws(() => Preferences.Default.Set("anything", new int[] { 1 })); +#if WINDOWS + [Fact] + public void DateTime_Supports_Reading_String_Compat() + { + // This is a special test where when unpackaged on windows in .NET 8 + // dates were stored as ToString but in .NET 6 they are stored as ToBinary. + // This test ensures that the compat layer is working correctly + // and that the date is read correctly regardless of the storage format. + // This test is only valid on windows unpackaged. + + if (ApplicationModel.AppInfoUtils.IsPackagedApp) + return; + + Preferences.Default.Set("datetime_compat", testDateTime.ToString(), null); + + var get = Preferences.Default.Get("datetime_compat", DateTime.MinValue, null); + + Assert.Equal(testDateTime, get); + } +#endif + [Theory] [InlineData("datetime1", null)] [InlineData("datetime1", sharedNameTestData)]