Skip to content

Commit

Permalink
Fall back to loading .NET 8 date strings
Browse files Browse the repository at this point in the history
Fixes #25930
  • Loading branch information
mattleibow committed Nov 21, 2024
1 parent dc5da7d commit d919503
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
10 changes: 7 additions & 3 deletions src/Essentials/src/Preferences/Preferences.uwp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -212,12 +212,16 @@ public T Get<T>(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;
}
Expand Down
21 changes: 21 additions & 0 deletions src/Essentials/test/DeviceTests/Tests/Preferences_Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,27 @@ public void DateTimePreservesKind(string sharedName, DateTimeKind kind)
public void FailsWithUnsupportedType() =>
Assert.Throws<NotSupportedException>(() => 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)]
Expand Down

0 comments on commit d919503

Please sign in to comment.