Skip to content
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
9 changes: 7 additions & 2 deletions src/Extensions/DateTimeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,18 @@ namespace WinUI.TableView.Extensions;
internal static class DateTimeExtensions
{
/// <summary>
/// Converts a DateTime to a DateTimeOffset using the local time zone.
/// Converts a DateTime to a DateTimeOffset, respecting the DateTime's Kind.
/// Uses UTC offset for UTC DateTimes and local offset otherwise.
/// </summary>
/// <param name="dateTime">The DateTime to convert.</param>
/// <returns>A DateTimeOffset representing the same point in time as the DateTime.</returns>
public static DateTimeOffset ToDateTimeOffset(this DateTime dateTime)
{
return new DateTimeOffset(dateTime, TimeZoneInfo.Local.GetUtcOffset(dateTime));
var offset = dateTime.Kind == DateTimeKind.Utc
? TimeSpan.Zero
: TimeZoneInfo.Local.GetUtcOffset(dateTime);

return new DateTimeOffset(dateTime, offset);
}

/// <summary>
Expand Down
9 changes: 9 additions & 0 deletions tests/DateTimeExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ public void ToDateTimeOffset_FromDateTime_UsesLocalOffset()
Assert.AreEqual(expected, dto);
}

[TestMethod]
public void ToDateTimeOffset_FromUtcDateTime_UsesZeroOffset()
{
var dt = new DateTime(2024, 1, 2, 3, 4, 5, DateTimeKind.Utc);
var dto = dt.ToDateTimeOffset();
var expected = new DateTimeOffset(dt, TimeSpan.Zero);
Assert.AreEqual(expected, dto);
}

[TestMethod]
public void ToDateTimeOffset_FromTimeSpan_UsesTodayDate()
{
Expand Down