Java日期处理汇总:Date、Calendar 、GregorianCalendar

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();
	}
	
}


2、调用测试

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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值