diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index ecbb657f3..59bef45bf 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -22,6 +22,7 @@
+ DateUtils.getFragmentInDays(Date, Calendar.MONTH) returns wrong days
DurationFormatUtils does not describe format string fully
DurationFormatUtils#lexx does not detect unmatched quote char
DurationFormatUtils does not handle large durations correctly
diff --git a/src/main/java/org/apache/commons/lang3/time/DateUtils.java b/src/main/java/org/apache/commons/lang3/time/DateUtils.java
index e57b53765..60bb0d0d6 100644
--- a/src/main/java/org/apache/commons/lang3/time/DateUtils.java
+++ b/src/main/java/org/apache/commons/lang3/time/DateUtils.java
@@ -1690,13 +1690,15 @@ public class DateUtils {
final long millisPerUnit = getMillisPerUnit(unit);
long result = 0;
+ int offset = (unit == Calendar.DAY_OF_YEAR) ? 0 : 1;
+
// Fragments bigger than a day require a breakdown to days
switch (fragment) {
case Calendar.YEAR:
- result += ((calendar.get(Calendar.DAY_OF_YEAR) -1) * MILLIS_PER_DAY) / millisPerUnit;
+ result += ((calendar.get(Calendar.DAY_OF_YEAR) - offset) * MILLIS_PER_DAY) / millisPerUnit;
break;
case Calendar.MONTH:
- result += ((calendar.get(Calendar.DAY_OF_MONTH) -1) * MILLIS_PER_DAY) / millisPerUnit;
+ result += ((calendar.get(Calendar.DAY_OF_MONTH) - offset) * MILLIS_PER_DAY) / millisPerUnit;
break;
default:
break;
diff --git a/src/test/java/org/apache/commons/lang3/time/DateUtilsFragmentTest.java b/src/test/java/org/apache/commons/lang3/time/DateUtilsFragmentTest.java
index dfd2e2741..de9d7c6f2 100644
--- a/src/test/java/org/apache/commons/lang3/time/DateUtilsFragmentTest.java
+++ b/src/test/java/org/apache/commons/lang3/time/DateUtilsFragmentTest.java
@@ -561,4 +561,32 @@ testResult);
/ DateUtils.MILLIS_PER_HOUR,
testResult);
}
+
+ @Test
+ public void testDaysOfMonthWithCalendar() throws Exception {
+ final long testResult = DateUtils.getFragmentInDays(aCalendar, Calendar.MONTH);
+ assertEquals(days, testResult);
+ }
+
+ @Test
+ public void testDaysOfMonthWithDate() throws Exception {
+ final long testResult = DateUtils.getFragmentInDays(aDate, Calendar.MONTH);
+ final Calendar cal = Calendar.getInstance();
+ cal.setTime(aDate);
+ assertEquals(cal.get(Calendar.DAY_OF_MONTH), testResult);
+ }
+
+ @Test
+ public void testDaysOfYearWithCalendar() throws Exception {
+ final long testResult = DateUtils.getFragmentInDays(aCalendar, Calendar.YEAR);
+ assertEquals(aCalendar.get(Calendar.DAY_OF_YEAR), testResult);
+ }
+
+ @Test
+ public void testDaysOfYearWithDate() throws Exception {
+ final long testResult = DateUtils.getFragmentInDays(aDate, Calendar.YEAR);
+ final Calendar cal = Calendar.getInstance();
+ cal.setTime(aDate);
+ assertEquals(cal.get(Calendar.DAY_OF_YEAR), testResult);
+ }
}