Skip to content

Commit

Permalink
Improved handling of DateTimeKind when converting form DateTimeOffSet…
Browse files Browse the repository at this point in the history
… to DateTime.

Related to question #897
  • Loading branch information
groogiam committed Mar 23, 2023
1 parent 91472bf commit a818395
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
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

0 comments on commit a818395

Please sign in to comment.