DateUtil
1.取得当前日期“年”,并判断此年是否为闰年
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(new Date());
int year2 = gc.get(Calendar.YEAR);
System.out.print(year2 + "为:" + gc.isLeapYear(year2));
2.得到某日,下一日,下一月等
//得到日
public static int getDay(Date date) {
Calendar calendar = Calendar. getInstance();
calendar.setTime(date);
return calendar.get(Calendar. DATE);
}
/**
* 取得两个日期之间的各天数日,开始日期会小于结束日期
* @param beginDate
* @param endDate
* @return
*/
public List<Date> getDates(Date beginDate, Date endDate) {
List<Date> list = new ArrayList<Date>();
Date nextDay = beginDate;
list.add(beginDate);
while(nextDay.before(endDate)) {
nextDay = nextDay(nextDay,1);
list.add(nextDay);
}
return list;
}
public static Date nextDay(Date date, int day) {
Calendar cal = Calendar. getInstance();
if (date != null) {
cal.setTime(date);
}
cal.add(Calendar. DAY_OF_YEAR, day);
return cal.getTime();
}
//得到下一月 months可以为正负整数或0
public static Date nextMonth(Date date, int months) {
Calendar cal = Calendar. getInstance();
if (date != null) {
cal.setTime(date);
}
cal.add(Calendar. MONTH, months);
return cal.getTime();
}
public static String nextDay( int day, String format) {
Calendar cal = Calendar. getInstance();
cal.setTime( new Date());
cal.add(Calendar. DAY_OF_YEAR, day);
return dateToString(cal.getTime(), format);
}
/**
* 把日期转换为字符串
*
* @param date
* @return
*/
public static String dateToString (java.util.Date date, String format) {
String result = "";
SimpleDateFormat formater = new SimpleDateFormat(format);
try {
result = formater.format(date);
} catch (Exception e) {
// log.error(e);
}
return result;
}
3.得到某年某月最大的天数
public static int getDaysOfMonth( int year, int month) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, 1);
return calendar.getActualMaximum(Calendar. DAY_OF_MONTH);
}
4.得到年
public static int getYear(Date date) {
Calendar calendar = Calendar. getInstance();
calendar.setTime(date);
return calendar.get(Calendar. YEAR);
}