Skip to content

Commit

Permalink
fix: Use DayNumber instead of DayOfYear to compare DateOnly instances (
Browse files Browse the repository at this point in the history
  • Loading branch information
hangy authored Feb 15, 2024
1 parent 5f30979 commit b8ace55
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
15 changes: 15 additions & 0 deletions src/Humanizer.Tests.Shared/DateOnlyHumanizeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,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 @@ -154,12 +154,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

0 comments on commit b8ace55

Please sign in to comment.