Add isSameDay method to DateUtils

git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/lang/trunk@137930 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Stephen Colebourne 2004-09-07 23:03:37 +00:00
parent e5e5fb3ebd
commit fc40d1cb65
2 changed files with 37 additions and 1 deletions

View File

@ -31,7 +31,7 @@ import java.util.TimeZone;
* @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a>
* @author Phil Steitz
* @since 2.0
* @version $Id: DateUtils.java,v 1.26 2004/09/07 22:50:45 scolebourne Exp $
* @version $Id: DateUtils.java,v 1.27 2004/09/07 23:03:37 scolebourne Exp $
*/
public class DateUtils {
@ -117,6 +117,28 @@ public class DateUtils {
public DateUtils() {
}
//-----------------------------------------------------------------------
/**
* <p>Checks if two calendar objects are on the same day ignoring time.</p>
*
* <p>28 Mar 2002 13:45 and 28 Mar 2002 06:01 would return true.
* 28 Mar 2002 13:45 and 12 Mar 2002 13:45 would return false.
* </p>
*
* @param cal1 the first calendar, not null
* @param cal1 the second calendar, not null
* @return true if they represent the same day
* @throws IllegalArgumentException if either calendar is <code>null</code>
*/
public static boolean isSameDay(Calendar cal1, Calendar cal2) {
if (cal1 == null || cal2 == null) {
throw new IllegalArgumentException("The date must not be null");
}
return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR));
}
//-----------------------------------------------------------------------
/**
* <p>Round this date, leaving the field specified as the most

View File

@ -21,6 +21,7 @@ import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.Locale;
import java.util.NoSuchElementException;
@ -151,6 +152,19 @@ public class DateUtilsTest extends TestCase {
assertEquals(false, Modifier.isFinal(DateUtils.class.getModifiers()));
}
//-----------------------------------------------------------------------
public void testIsSameDay() {
GregorianCalendar cal1 = new GregorianCalendar(2004, 6, 9, 13, 45);
GregorianCalendar cal2 = new GregorianCalendar(2004, 6, 9, 13, 45);
assertEquals(true, DateUtils.isSameDay(cal1, cal2));
cal2.add(Calendar.DAY_OF_YEAR, 1);
assertEquals(false, DateUtils.isSameDay(cal1, cal2));
cal1.add(Calendar.DAY_OF_YEAR, 1);
assertEquals(true, DateUtils.isSameDay(cal1, cal2));
cal2.add(Calendar.YEAR, 1);
assertEquals(false, DateUtils.isSameDay(cal1, cal2));
}
//-----------------------------------------------------------------------
/**
* Tests various values with the round method