package com; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; public class DateUtil { /** * 获取本月第一天 * @return 当前月第一天的日期 */ public static String getMonthFirstDay() { Calendar cal = Calendar.getInstance(); Calendar f = (Calendar) cal.clone(); f.clear(); f.set(Calendar.YEAR, cal.get(Calendar.YEAR)); f.set(Calendar.MONTH, cal.get(Calendar.MONTH)); String firstday = new SimpleDateFormat("yyyy-MM-dd").format(f.getTime()); return firstday; } /** * 获取本月最后一天 * @return 当前月最后一天的日期 */ public static String getMonthLastDay() { Calendar cal = Calendar.getInstance(); Calendar l = (Calendar) cal.clone(); l.clear(); l.set(Calendar.YEAR, cal.get(Calendar.YEAR)); l.set(Calendar.MONTH, cal.get(Calendar.MONTH) + 1); l.set(Calendar.MILLISECOND, -1); String lastday = new SimpleDateFormat("yyyy-MM-dd").format(l.getTime()); return lastday; } /** * 根据日期计算某月有多少天 * @param date 需要计算有多少天的日期 * @return 返回当前日期的天数 */ public static int getDays(String date){ SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Calendar objCalendar = new GregorianCalendar(); try { objCalendar.setTime(formatter.parse(date)); int days = objCalendar.getActualMaximum(Calendar.DAY_OF_MONTH); return days; } catch (Exception e1) { e1.printStackTrace(); } return 0; } }
测试:
package com.test; import org.junit.Test; import com.DateUtil; public class DateTest { @Test public void test(){ System.out.println("本月第一天是:"+DateUtil.getMonthFirstDay()); } @Test public void test2(){ System.out.println("本月最后一天是:"+DateUtil.getMonthLastDay()); } @Test public void test3(){ String str = "2012-08-15"; int days = DateUtil.getDays(str); System.out.println(str+"这个月共有"+days); } }
运行效果: