Java examples for java.util:Month
Compare both dates and uses only year and month for comparing.
//package com.java2s; import java.util.Calendar; import java.util.Date; public class Main { public static void main(String[] argv) throws Exception { Date date1 = new Date(); Date date2 = new Date(); System.out.println(compareMonthYear(date1, date2)); }//from w w w .ja v a 2s . com /** * Compare both dates and uses only year and month for comparing. * * @param date1 * must not be <code>null</code> * @param date2 * must not be <code>null</code> * @return <code>0</code>, if both dates (using year and month) are equals; * <code>1</code>, if <code>date1</code> is later than * <code>date2</code>; else <code>-1</code> */ public static int compareMonthYear(Date date1, Date date2) { final Calendar cal = Calendar.getInstance(); cal.setTime(date1); final int month1 = cal.get(Calendar.MONTH); final int year1 = cal.get(Calendar.YEAR); cal.setTime(date2); final int month2 = cal.get(Calendar.MONTH); final int year2 = cal.get(Calendar.YEAR); return year1 < year2 ? -1 : (year1 > year2 ? 1 : (month1 < month2 ? -1 : (month1 > month2 ? 1 : 0))); } }