import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateTime { public static void main(String[] args) throws ParseException { DateTime dt = new DateTime(); Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2008-02-14"); date = dt.lastDayOfMonth(date); System.out.println (new SimpleDateFormat("yyyy-MM-dd").format(date)); date = new SimpleDateFormat("yyyy-MM-dd").parse("2008-02-14"); date = dt.lastDayOfMonth2(date); System.out.println (new SimpleDateFormat("yyyy-MM-dd").format(date)); date = new SimpleDateFormat("yyyy-MM-dd").parse("2008-02-14"); date = dt.lastDayOfMonth3(date); System.out.println (new SimpleDateFormat("yyyy-MM-dd").format(date)); date = new SimpleDateFormat("yyyy-MM-dd").parse("2008-02-14"); date = dt.lastDayOfMonth4(date); System.out.println (new SimpleDateFormat("yyyy-MM-dd").format(date)); } public Date lastDayOfMonth(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.set(Calendar.DAY_OF_MONTH, 1); cal.roll(Calendar.DAY_OF_MONTH, -1); return cal.getTime(); } public Date lastDayOfMonth2(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); int value = cal.getActualMaximum(Calendar.DAY_OF_MONTH); cal.set(Calendar.DAY_OF_MONTH, value); return cal.getTime(); } public Date lastDayOfMonth3(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.set(Calendar.DAY_OF_MONTH, 1); cal.add(Calendar.MONTH, 1); cal.add(Calendar.DATE, -1); return cal.getTime(); } public Date lastDayOfMonth4(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); do { cal.add(Calendar.DATE, 1); } while (cal.get(Calendar.DATE) != 1); cal.add(Calendar.DATE, -1); return cal.getTime(); } } |
输入日期:
2008-02-14
输出结果:
2008-02-29
2008-02-29
2008-02-29
2008-02-29