Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fall back to loading .NET 8 date strings #26033

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 9 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
Loading