Skip to content

Instantly share code, notes, and snippets.

@letsspeak
Last active December 11, 2017 07:48
Show Gist options
  • Save letsspeak/80751987f5776ffd779158e58a44071a to your computer and use it in GitHub Desktop.
Save letsspeak/80751987f5776ffd779158e58a44071a to your computer and use it in GitHub Desktop.
Java Calendar add can beyond the XXX_OF boundary and Calendar date comparision test code
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class MyClass {
public static void main(String args[]) {
// Don be afraid that add(DAY_OF〜, value) makes no differences
Calendar calendar1 = GregorianCalendar.getInstance();
calendar1.set(Calendar.MONTH, 11); // = December (0 start value)
calendar1.set(Calendar.DAY_OF_MONTH, 31);
calendar1.add(Calendar.DATE, 1);
printCalendarDate(calendar1); // => 2018-01-01
Calendar calendar2 = GregorianCalendar.getInstance();
calendar2.set(Calendar.MONTH, 11); // = December (0 start value)
calendar2.set(Calendar.DAY_OF_MONTH, 31);
calendar2.add(Calendar.DAY_OF_MONTH, 1);
printCalendarDate(calendar2); // => 2018-01-01
Calendar calendar3 = GregorianCalendar.getInstance();
calendar3.set(Calendar.MONTH, 11); // = December (0 start value)
calendar3.set(Calendar.DAY_OF_MONTH, 31);
calendar3.add(Calendar.DAY_OF_YEAR, 1);
printCalendarDate(calendar3); // => 2018-01-01
System.out.println("calendar1.equals(calendar2) = " + (calendar1.equals(calendar2) ? "true" : "false")); // => false
System.out.println("calendar2.equals(calendar3) = " + (calendar2.equals(calendar3) ? "true" : "false")); // => false
System.out.println("calendar3.equals(calendar1) = " + (calendar3.equals(calendar1) ? "true" : "false")); // => false
System.out.println("isEqualsDate(calendar1, calendar2) = " + (isEqualDate(calendar1, calendar2) ? "true" : "false")); // => true
System.out.println("isEqualsDate(calendar2, calendar3) = " + (isEqualDate(calendar2, calendar3) ? "true" : "false")); // => true
System.out.println("isEqualsDate(calendar3, calendar1) = " + (isEqualDate(calendar3, calendar1) ? "true" : "false")); // => true
}
public static void printCalendarDate(Calendar calendar) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateString = sdf.format(calendar.getTime());
System.out.println(dateString);
}
public static boolean isEqualDate(Calendar c1, Calendar c2) {
return c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)
&& c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment