From b81c980a351cf85743afb22525d2d850a8fc5f3f Mon Sep 17 00:00:00 2001 From: Michael Keppler Date: Thu, 12 Oct 2017 09:38:31 +0200 Subject: [PATCH] Avoid bad rounding "1 year, 12 months" in date formatter Round first, then calculate the labels. This avoids "x years, 12 months" and instead produces "x+1 years". One test case has been added for the original example the bug was found with, and one assertion has been moved from an existing test case to the new test case, since it also triggered the bug. Bug: 525907 Change-Id: I3270af3850c4fb7bae9123a0a6582f93055c9780 Signed-off-by: Michael Keppler Signed-off-by: Matthias Sohn --- .../org/eclipse/jgit/util/RelativeDateFormatterTest.java | 9 ++++++++- .../src/org/eclipse/jgit/util/RelativeDateFormatter.java | 5 +++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/RelativeDateFormatterTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/RelativeDateFormatterTest.java index 76687d15a..fb76ec4e5 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/RelativeDateFormatterTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/RelativeDateFormatterTest.java @@ -128,7 +128,14 @@ public class RelativeDateFormatterTest { assertFormat(380, DAY_IN_MILLIS, "1 year, 1 month ago"); assertFormat(410, DAY_IN_MILLIS, "1 year, 2 months ago"); assertFormat(2, YEAR_IN_MILLIS, "2 years ago"); - assertFormat(1824, DAY_IN_MILLIS, "4 years, 12 months ago"); + } + + @Test + public void testFullYearMissingSomeDays() { + // avoid "x year(s), 12 months", as humans would always round this up to + // "x+1 years" + assertFormat(5 * 365 + 1, DAY_IN_MILLIS, "5 years ago"); + assertFormat(2 * 365 - 10, DAY_IN_MILLIS, "2 years ago"); } @Test diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/util/RelativeDateFormatter.java b/org.eclipse.jgit/src/org/eclipse/jgit/util/RelativeDateFormatter.java index 21a55a602..a5df66e99 100644 --- a/org.eclipse.jgit/src/org/eclipse/jgit/util/RelativeDateFormatter.java +++ b/org.eclipse.jgit/src/org/eclipse/jgit/util/RelativeDateFormatter.java @@ -114,10 +114,11 @@ public class RelativeDateFormatter { // up to 5 years use "year, months" rounded to months if (ageMillis < 5 * YEAR_IN_MILLIS) { - long years = ageMillis / YEAR_IN_MILLIS; + long years = round(ageMillis, MONTH_IN_MILLIS) / 12; String yearLabel = (years > 1) ? JGitText.get().years : // JGitText.get().year; - long months = round(ageMillis % YEAR_IN_MILLIS, MONTH_IN_MILLIS); + long months = round(ageMillis - years * YEAR_IN_MILLIS, + MONTH_IN_MILLIS); String monthLabel = (months > 1) ? JGitText.get().months : // (months == 1 ? JGitText.get().month : ""); //$NON-NLS-1$ return MessageFormat.format(