public abstract class Calendar 说明Calendar类是一个抽象类,从api中可看出来,GregorianCalendar是Calendar类的唯一实现类。
Date类中,多数的方法都已经成为Deprecated,所以,我们在使用的时候,可以用Calendar类来设置好我们需要的时间之后,用Calendar类的getTime方法来取得这个Date对象。
1、工具类
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* 日期工具类
* @author xueji
*
*/
public class DateUtil {
/**
* 获取当前时间
* @return
*/
public static Date getCurrentTime(){
Calendar cal = Calendar.getInstance();
return cal.getTime();
}
/**
* 获取当前日期
* @return
*/
public static Date getCurrentDate(){
return getCurrentDate(0, 0, 0);
}
/**
* 获取当前日期,自定义时间
* @return
*/
public static Date getCurrentDate(int hour, int minute, int second){
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, second);
return cal.getTime();
}
/**
* 获取给定时间几天后的时间
* @param beginDate
* @param addDay
* @return
*/
public static Date getAfterDate(Date beginDate, int addDay) {
Calendar cal = Calendar.getInstance();
cal.setTime(beginDate);
cal.add(Calendar.DATE, addDay);
return cal.getTime();
}
/**
* 计算两个时间差(endDate-beginDate)
* @param beginDate
* @param endDate
* @return
*/
public static long getSubDate(Date beginDate, Date endDate){
return endDate.getTime() - beginDate.getTime();
}
/**
* 获得上周星期日的日期
* @return
*/
public static Date getLastWeekSunday(){
Calendar cal = Calendar.getInstance();
//将每周第一天设为星期一,默认是星期天
cal.setFirstDayOfWeek(Calendar.MONDAY);
//周数减一,即上周
cal.add(Calendar.WEEK_OF_MONTH, -1);
//设为星期天
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
return cal.getTime();
}
}
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(sdf.format(getCurrentTime()));
System.out.println(sdf.format(getCurrentDate()));
System.out.println(sdf.format(getCurrentDate(10,10,5)));
System.out.println(sdf.format(getAfterDate(new Date(), 5)));
System.out.println(getSubDate(getCurrentTime(), getAfterDate(new Date(), 5)) / (24*3600*1000));
System.out.println(sdf.format(getLastWeekSunday()));
}
3、运行的结果
2014-10-01 13:00:35
2014-10-01 00:00:00
2014-10-01 10:10:05
2014-10-06 13:00:35
5
2014-09-28 13:00:35