Java中对日期操作
//1.获得当前日期中的月头月末时间
public Date getLastDayOfMonth(Date d) {
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
return cal.getTime();
}
public Date getFirstDayOfMonth(Date d) {
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.set(Calendar.DAY_OF_MONTH, 1);
return cal.getTime();
}
public static String formatDate(Date aDate, String dateformat) {
SimpleDateFormat bartDateFormat = new SimpleDateFormat(dateformat);
return bartDateFormat.format(aDate);
}
public static void main(String[] args) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d = sdf.parse("2012-02-05");
//Date d=new Date();
System.out.println(formatDate(getFirstDayOfMonth(d), "yyyy-MM-dd")+"~"+formatDate(getLastDayOfMonth(d), "yyyy-MM-dd"));
}
//2.当前日期向前移
Calendar cdweek = Calendar.getInstance();
cdweek.add(Calendar.DATE, -7);
Date d = cdweek.getTime();
//3.比较2个日期
Date fileDate = cd.getTime();
//一周前的时间与文件的创建时间比较,如果为true表示文件的创建时间早于一周前,那么需要删除
boolean flag = fileDate.before(d);
//4.日期向前推
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//now = sdf.parse("2012-05-1 12:25:23");
Calendar cal = Calendar.getInstance();
cal.setTime(now);
cal.add(Calendar.MONTH,-1);
now = cal.getTime();