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

fix: Use DayNumber instead of DayOfYear to compare DateOnly instances #1228

Merged
merged 1 commit into from
Feb 15, 2024
Merged
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
15 changes: 15 additions & 0 deletions src/Humanizer.Tests.Shared/DateOnlyHumanizeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,21 @@ public void DefaultStrategy_DaysAgo()
Assert.Equal(expectedResult, actualResult);
}

[Fact]
public void DefaultStrategy_YearsAgo()
{
Configurator.DateOnlyHumanizeStrategy = new DefaultDateOnlyHumanizeStrategy();

var baseDate = DateTime.Now;
var inputTime = DateOnly.FromDateTime(baseDate.AddMonths(-24));
var baseTime = DateOnly.FromDateTime(baseDate);

const string expectedResult = "2 years ago";
var actualResult = inputTime.Humanize(baseTime);

Assert.Equal(expectedResult, actualResult);
}

[Fact]
public void PrecisionStrategy_NextDay()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,12 +155,12 @@ public static string DefaultHumanize(DateTime input, DateTime comparisonBase, Cu
public static string DefaultHumanize(DateOnly input, DateOnly comparisonBase, CultureInfo culture)
{
var tense = input > comparisonBase ? Tense.Future : Tense.Past;
var diffDays = Math.Abs(comparisonBase.DayOfYear - input.DayOfYear);
var diffDays = Math.Abs(comparisonBase.DayNumber - input.DayNumber);
var ts = new TimeSpan(diffDays, 0, 0, 0);

var sameMonth = comparisonBase.AddMonths(tense == Tense.Future ? 1 : -1) == input;

var days = Math.Abs(input.DayOfYear - comparisonBase.DayOfYear);
var days = Math.Abs(input.DayNumber - comparisonBase.DayNumber);

return DefaultHumanize(ts, sameMonth, days, tense, culture);
}
Expand Down