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

Improved handling of DateTimeKind when converting form DateTimeOffSet to DateTime. #898

Open
wants to merge 1 commit 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
2 changes: 1 addition & 1 deletion src/Simple.OData.Client.Core/Cache/TypeCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ public bool TryConvert(object? value, Type targetType, out object? result)
}
else if ((targetType == typeof(DateTime) || targetType == typeof(DateTime?)) && value is DateTimeOffset offset)
{
result = offset.DateTime;
result = offset.Offset == default ? offset.UtcDateTime : offset.DateTime;
}
else if ((targetType == typeof(DateTime) || targetType == typeof(DateTime?)) && ImplicitConversionTo<DateTime>(value) is MethodInfo implicitMethod)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,42 @@ public void TryConvert(object value, Type sourceType, Type targetType)
Assert.Equal(ChangeType(sourceValue, sourceType), ChangeType(targetValue, sourceType));
}

[Fact]
public void TryConvert_Should_Use_DateTimeKind_Utc_For_Utc_DateTimeOffset()
{
var toConvert = DateTimeOffset.UtcNow;

TypeCache.TryConvert(toConvert, typeof(DateTime), out var result);

var resultTyped = (DateTime)result;

Assert.Equal(DateTimeKind.Utc, resultTyped.Kind);

TypeCache.TryConvert(toConvert, typeof(DateTime?), out var resultNullable);

var resultNullableTyped = (DateTime?)result;

Assert.Equal(DateTimeKind.Utc, resultNullableTyped.Value.Kind);
}

[Fact]
public void TryConvert_Should_Use_DateTimeKind_Unspecified_For_Non_Utc_DateTimeOffset()
{
var toConvert = DateTimeOffset.Now;

TypeCache.TryConvert(toConvert, typeof(DateTime), out var result);

var resultTyped = (DateTime)result;

Assert.Equal(DateTimeKind.Unspecified, resultTyped.Kind);

TypeCache.TryConvert(toConvert, typeof(DateTime?), out var resultNullable);

var resultNullableTyped = (DateTime?)result;

Assert.Equal(DateTimeKind.Unspecified, resultNullableTyped.Value.Kind);
}

[Fact]
public void TryConvert_GeographyPoint()
{
Expand Down