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 3cd4b4bbc..f75d7bf48 100644 --- a/src/main/java/org/apache/commons/lang3/time/DateUtils.java +++ b/src/main/java/org/apache/commons/lang3/time/DateUtils.java @@ -621,6 +621,20 @@ public class DateUtils { c.set(calendarField, amount); return c.getTime(); } + + //----------------------------------------------------------------------- + /** + * Convert a Date into a Calendar object. + * + * @param date the date to convert to a Calendar + * @return the created Calendar + * @throws NullPointerException if null is passed in + */ + public static Calendar toCalendar(Date date) { + Calendar c = Calendar.getInstance(); + c.setTime(date); + return c; + } //----------------------------------------------------------------------- /** diff --git a/src/test/java/org/apache/commons/lang3/time/DateUtilsTest.java b/src/test/java/org/apache/commons/lang3/time/DateUtilsTest.java index f01ed28a7..cfb42219b 100644 --- a/src/test/java/org/apache/commons/lang3/time/DateUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/time/DateUtilsTest.java @@ -597,6 +597,17 @@ public class DateUtilsTest extends TestCase { assertEquals(mil, cal.get(Calendar.MILLISECOND)); } + //----------------------------------------------------------------------- + public void testToCalendar() { + assertEquals("Failed to convert to a Calendar and back", date1, DateUtils.toCalendar(date1).getTime()); + try { + DateUtils.toCalendar(null); + fail("Expected NullPointerException to be thrown"); + } catch(NullPointerException npe) { + // expected + } + } + //----------------------------------------------------------------------- /** * Tests various values with the round method