Java_处理日期的工具类

开发中,我们经常需要获取时间戳,对时间进行格式化,处理时间加减等各种问题,这里整合了一下我常碰到的时间处理的情况,写了一个工具类:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Vector;

/**
 * @function 日期处理工具
 * @author Ricky
 */
public class DateExtraUtils {
	
	public static final String DATETIME = "yyyy-MM-dd HH:mm:ss";
	public static final String DATE = "yyyy-MM-dd";
	public static final String DATEYEAR = "yyyy";
	public static final String DATEMONTH = "yyyy-MM";
	public static final String DATEHMS = "HH:mm:ss";
	public static final String DATEHOUR = "yyyy-MM-dd-HH";
	public static final String DATETIMETIGHT = "yyyyMMddHHmmss";
	
	/**
	 * @function 将日期转换成字符串"yyyy-MM-dd"
	 * @param date 日期
	 * @return 日期字符串
	 */
	public static String formatDate(Date date) {
		if(date==null){
			date = Calendar.getInstance().getTime();
		}
		return formatDate(date,DATE);
	}
	
	
	/**
	 * @function 将日期转换成字符串
	 * @param DATETIME 日期
	 * @return 日期字符串
	 */
	public static Date parseDateTime(String dateStr) {
		return parseDate(dateStr,DATETIME);
	}
	
	/**
	 * @function 将日期转换成字符串
	 * @param year
	 * @return
	 */
	public static Date parseDateYear(String year){
		return parseDate(year,DATEYEAR);
	}
	
	/**
	 * @function 将日期转换成字符串
	 * @param date 日期
	 * @param pattern 格式
	 * @return 日期字符串
	 */
	public static String formatDate(Date date,String pattern) {
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(date);
	}
	
	/**
	 * @function 将字符串转换成日期
	 * @param date 日期形式的字符串
	 * @return 日期
	 */
	public static Date createDateFromString(String date){
		if(date==null) return null;
		String[] d = date.split("-");
		Calendar ca = Calendar.getInstance();
		ca.set(Calendar.YEAR, Integer.parseInt(d[0]));
		ca.set(Calendar.MONTH, Integer.parseInt(d[1])-1);
		ca.set(Calendar.DAY_OF_MONTH, Integer.parseInt(d[2]));
		return ca.getTime();
	}
	
	/**
	 * @function 获取带有年份的向量
	 * @return 向量
	 */
	@SuppressWarnings({"unchecked","rawtypes"})
	public static Vector getYears() {
		Calendar cd = Calendar.getInstance();
	 	Vector years = new Vector();
		for(int i = cd.get(Calendar.YEAR); i >= 2000; i --){
			years.add(new Integer(i));
		}
		return years;
	}
	
	/**
	 * @function 获取年份列表
	 * @param begin 开始年份
	 * @param end 结束年份
	 * @return 年份列表
	 */
	@SuppressWarnings({"unchecked","rawtypes"})
	public static Vector getBetweenYears(int begin, int end) {
		Vector years = new Vector();
		for (int i = begin; i <= end; i ++) {
			years.add(new Integer(i));
		}
		return years;
	}
	
	/**
	 * @function 获取带有年份的向量
	 * @param begin 开始年份
	 * @param end 结束年份
	 * @return 向量
	 */
	@SuppressWarnings({"unchecked","rawtypes"})
	public static Vector getYears(int begin, int end) {
		Vector years = new Vector();
		for (int i = end; i >= begin; i --) {
			years.add(new Integer(i));
		}
		return years;
	}
	
	/**
	 * @function 获取带有年份的向量
	 * @param begin 开始年份
	 * @return 向量
	 */
	@SuppressWarnings({"unchecked","rawtypes"})
	public static Vector getYears(int begin) {
		Calendar cd = Calendar.getInstance();
	 	Vector years = new Vector();
		for(int i = cd.get(Calendar.YEAR); i >= begin; i --){
			years.add(new Integer(i));
		}
		return years;
	}
	
	/**
	 * @function 获取按年为间隔的日期
	 * @param year
	 * @param n
	 * @return
	 */
	public static String getAnyBeforeYear(String rptdate,int n){	
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
		Calendar cd = Calendar.getInstance();
		cd.setTime(parseDate(rptdate));
		
		cd.add(Calendar.YEAR, - n);
		String beforeDate=format.format(cd.getTime()); 	
		return beforeDate;
	}
	
	
	/**
	 * 获取n天后的日期
	 * @param rptdate
	 * @param n
	 * @return
	 */
	public static Date getTheNextDate(Date rptdate,int n){	
		Calendar cd = Calendar.getInstance();
		cd.setTime(rptdate);	
		cd.add(Calendar.DATE, n);		 	
		return cd.getTime();
	}
	
	/**
	 * 获取n月后的日期
	 * @param rptdate
	 * @param n
	 * @return
	 */
	public static Date getTheNextMonth(Date rptdate,int n){	
		Calendar cd = Calendar.getInstance();
		cd.setTime(rptdate);	
		cd.add(Calendar.MONTH, n);		 	
		return cd.getTime();
	}
	
	/**
	 * @function 获取带有月份的向量
	 * @return 向量
	 */
	@SuppressWarnings({"unchecked","rawtypes"})
	public static Vector getMonths() {
    	Vector months = new Vector(12);
		for(int i=1;i<=12;i++){
			months.add(new Integer(i));
		}
		return months;
	}
	
	/**
	 * @function 获取带有月份的向量
	 * @param begin 开始月份
	 * @return 向量
	 */
	@SuppressWarnings({"unchecked","rawtypes"})
	public static Vector getMonths(int begin){
		Calendar cd = Calendar.getInstance();
		Vector months = new Vector();
		for(int i = cd.get(Calendar.MONTH); i>=begin; i--){
			months.add(new Integer(i));
		}
		return months;
	}
	
	/**
	 * @function 获得最近一个周五
	 * @return 日期
	 * @throws Exception
	 */
	public static Date getLatestFriday() throws Exception{
		Calendar cd = Calendar.getInstance();
		cd.setTime(DateExtraUtils.parseDate(DateExtraUtils.formatDate(cd.getTime())));	
        // 获得最近一个周五
        int day = cd.get(Calendar.DAY_OF_WEEK);
        if (day > 6) {
        	cd.add(Calendar.DATE, -day + 6);
        } else {
            cd.add(Calendar.DATE, -day - 1);
        }
        return cd.getTime();
	}
	
	/**
	 * @function 获取四季向量
	 * @return 向量
	 */
	@SuppressWarnings({"unchecked","rawtypes"})
	public static Vector getSeason(){
		Vector season = new Vector(4);
		for(int i=1;i<=4;i++){
			season.add(new Integer(i));
		}
		return season;
	}
	
	/**
	 * @function 获取当前日期的上一天
	 * @return 日期
	 */
	public static Date getYesterday() {
		Calendar cd = Calendar.getInstance();
		cd.add(Calendar.DATE, - 1);
		return cd.getTime();
	}
	
	/**
	 * @function 如果date比当前时间早,返回true;反之返回false
	 * @param date 日期
	 * @return boolean
	 */
	public static boolean isBypastTime(Date date) {
		Calendar cd1 = Calendar.getInstance();
		Calendar cd2 = Calendar.getInstance();
		cd2.setTime(date);
		return cd1.after(cd2);
	}
	
	/**
	 * 获得最近的旬报日期
	 * @param Calendar date 日期
	 * @return Date
	 */
	public static Date getNearestTensDay(Calendar date){
		Calendar nearestTensDay = date;
		int day = date.get(Calendar.DATE);
		if(day >= 21){
			nearestTensDay.set(Calendar.DATE, 21);
		}else if(day >= 11){
			nearestTensDay.set(Calendar.DATE, 11);
		}else{
			nearestTensDay.set(Calendar.DATE, 1);
		}
		return nearestTensDay.getTime();
	}
	
	/**
	 * 获得未来最近的旬8日日期(储备糖用)
	 * @param Calendar date
	 * @return Date
	 */
	public static Date getNearestTensEightDay(Calendar date){
		Calendar nearestTensDay = date;
		int day = date.get(Calendar.DATE);
		if(day >= 28){
			nearestTensDay.set(Calendar.DATE, 28);
		}else if(day >= 18){
			nearestTensDay.set(Calendar.DATE, 18);
		}else if(day >= 8){
			nearestTensDay.set(Calendar.DATE, 8);
		}else{
			nearestTensDay.add(Calendar.MONTH, -1);
			nearestTensDay.set(Calendar.DATE, 28);
		}
		return nearestTensDay.getTime();
	}
	
	/**
	 * 获得过去最近的上报日期
	 * @param Calendar date
	 * @return Date
	 */
	public static Date getLastestTensEightDay(Calendar date){
		Calendar nearestTensDay = date;
		int day = date.get(Calendar.DATE);
		if(day >= 19){
			nearestTensDay.set(Calendar.DATE, 18);
		}else if(day >= 9){
			nearestTensDay.set(Calendar.DATE, 8);
		}else{
			nearestTensDay.add(Calendar.MONTH, -1);
			nearestTensDay.set(Calendar.DATE, 28);
		}
		return nearestTensDay.getTime();
	}
	
    /**
     * 将字符串转换为日期
     * @param dateStr 日期形式的字符串
     * @return 日期
     */
    public static Date parseDate(String dateStr){
		return parseDate(dateStr,DATE);
	}
    
    /**
     * 将字符串转换为日期
     * @param dateStr 日期形式的字符串
     * @param pattern 日期类型
     * @return 日期
     */
    public static Date parseDate(String dateStr,String pattern){
			SimpleDateFormat sdf = new SimpleDateFormat(pattern);			
			try {
				return sdf.parse(dateStr);
			} catch (ParseException e) {
				return null;
			}		
	}
    
	/**
	 * 判断是否为每旬的第一天
	 * @param date 日期
	 * @return boolean
	 */
	public static boolean isTendaysTime(Date date){				
		int year=0;
		int month=0;
		int day=0;
		int nowyear=0;
		int nowmonth=0;
		int nowday=0;
		
		Calendar cd1 = Calendar.getInstance();
		Calendar cd2 = Calendar.getInstance();
		cd2.setTime(date);		
		year=cd2.get(Calendar.YEAR);
		month=cd2.get(Calendar.MONTH)+1;
		day=cd2.get(Calendar.DAY_OF_MONTH);
		
		nowyear=cd1.get(Calendar.YEAR);
		nowmonth=cd1.get(Calendar.MONTH)+1;
		nowday=cd1.get(Calendar.DAY_OF_MONTH);
		
		if(year<nowyear){
			return true;
		}
		else if(year==nowyear){
			if(month>nowmonth){
				return false;
			}
			else if(month<nowmonth){
				return true;
			}
			else if(month==nowmonth){    //当前月
				if(day<=1&&day<=10){             //上旬
					if(nowday>=9){
						return true;
					}
				}
				else if(day>=11&&day<=20){        //中旬
					if(nowday>=19){
						return true;
					}
				}
				else if(day>20){
					if(month==2){
						if(nowday>=25){
							return true;
						}
					}
					else{
						if(nowday>=29){
							return true;
						}
					}					
				}
			}
		}
		return false;
	}
	
	/**
	 * @function 获取四季向量
	 * @return 向量
	 */	
	@SuppressWarnings({"unchecked","rawtypes"})
	public static Vector getSeasons(){
		Vector seasons = new Vector(4);
		for(int i=1;i<=4;i++){
			seasons.add(new Integer(i));
		}
		return seasons;
	}
	
	/**
	 * 获取离ca最近的一个旬开始日期
	 * @param ca 日期
	 * @return 日期
	 */
	public static Date getLastTenDay(Calendar ca){
		Calendar lastCa = Calendar.getInstance();
		lastCa = ca;
		if(ca.get(Calendar.DATE)==1){
			lastCa.add(Calendar.MONTH, -1);
			lastCa.set(Calendar.DATE, 21);
		}else{
			lastCa.add(Calendar.DATE, -10);
		}
		return lastCa.getTime();
	}
	
	
	
	/**
	 * 获取n个月之前的事件
	 * @param date 日期
	 * @param n 月数
	 * @return Date
	 */
	public static Date getAnyBeforeMonth(Date date, int n) {
		Calendar ca = Calendar.getInstance();
		ca.setTime(date);
		ca.add(Calendar.MONTH, - n);
		return ca.getTime();
	}
	

	/**
	 * 获得季度报表中的年选择日期
	 * @return 
	 */
	public static String getSeasonYear() {
		Calendar ca = Calendar.getInstance();
		int month = ca.get(Calendar.MONTH)+1;
		if(month >= 1 && month < 4){
			ca.add(Calendar.YEAR, -1);
		}
		return formatDate(ca.getTime(),"yyyy");
	}
	
	/**
	 * 获得季度报表日期
	 * @return 
	 */
	public static String getSeasonReportDate() {
		Calendar ca = Calendar.getInstance();
		int month = ca.get(Calendar.MONTH)+1;
		String quarter="";
		if(month >= 4 && month < 7){
			quarter = "01";
		}else if(month >= 7 && month < 10){
			quarter = "04";
		}else if(month >= 10 || month < 1){
			quarter = "07";
		}else if(month >= 1 && month < 4){
			quarter = "10";
		}
		return quarter;
	}
	/**
	 * 获得季度报表日期
	 * @return 
	 */
	public static String getSeasonReportDateByDate(Date date) {
		Calendar ca = Calendar.getInstance();
		ca.setTime(date);
		int month = ca.get(Calendar.MONTH)+1;
		String quarter="";
		if(month >= 4 && month < 7){
			quarter = "01";
		}else if(month >= 7 && month < 10){
			quarter = "04";
		}else if(month >= 10){
			quarter = "07";
		}else if(month >= 1 && month < 4){
			quarter = "10";
		}
		return quarter;
	}
	
	/**
	 * 获得两个日期之间的month列表
	 * @param beginDate
	 * @param endDate
	 * @return
	 */
	public static List<String> getMonthsByBeginAndEndDate(Date beginDate, Date endDate) {
		if (beginDate == null || endDate == null || beginDate.after(endDate)) {
			return null;
		}
		List<String> months = new ArrayList<String>();
		Calendar beginCa = Calendar.getInstance();
		beginCa.setTime(beginDate);
		beginCa.set(Calendar.DATE, 1);
		Calendar endCa = Calendar.getInstance();
		endCa.setTime(endDate);
		endCa.set(Calendar.DATE, 1);
		int monthSize = getMonthSize(beginCa.getTime(), endCa.getTime());
		for(int i = 0; i < monthSize; i++) {
			months.add(formatDate(beginCa.getTime(),DATEMONTH));
			beginCa.add(Calendar.MONTH, 1);			
		}
		months.add(formatDate(beginCa.getTime(),DATEMONTH));
		return months;
	}
	
	/**
	 * 获得两个日期之间的day列表
	 * @param beginDate
	 * @param endDate
	 * @return
	 */
	public static List<String> getDaysByBeginAndEndDate(Date beginDate, Date endDate) {
		if (beginDate == null || endDate == null || beginDate.after(endDate)) {
			return null;
		}
		List<String> days = new ArrayList<String>();
		Calendar beginCa = Calendar.getInstance();
		beginCa.setTime(beginDate);
		Calendar endCa = Calendar.getInstance();
		endCa.setTime(endDate);
		int daySize = getGapOfTwoDate(beginCa.getTime(), endCa.getTime());
		for(int i = 0; i < daySize; i++) {
			days.add(formatDate(beginCa.getTime(),DATE));
			beginCa.add(Calendar.DAY_OF_MONTH, 1);			
		}
		days.add(formatDate(beginCa.getTime(),DATE));
		return days;
	}
	
	/**
	 * 获得两个日期之间月的个数
	 * @param s
	 * @param e
	 * @return
	 */
	public static int getMonthSize(Date s,Date e){
		if(s.after(e)){
			Date t=s;
			s=e;
			e=t;
		}
		Calendar start = Calendar.getInstance();
		start.setTime(s);
		Calendar end = Calendar.getInstance();
		end.setTime(e);
		Calendar temp=Calendar.getInstance();
		temp.setTime(e);
		temp.add(Calendar.DATE,1);

		int y=end.get(Calendar.YEAR)-start.get(Calendar.YEAR);
		int m=end.get(Calendar.MONTH)-start.get(Calendar.MONTH);

		if((start.get(Calendar.DATE)==1) && (temp.get(Calendar.DATE)==1)){
			return y*12+m+1;
		} else if((start.get(Calendar.DATE)!=1) && (temp.get(Calendar.DATE)==1)){
			return y*12+m;
		}
		else if((start.get(Calendar.DATE)==1) && (temp.get(Calendar.DATE)!=1)){
			return y*12+m;
		} else {
			return (y*12+m-1)<0?0:(y*12+m-1);
		}
	}
	/**
	 * 比较两个日期的大小
	 * author:sdarmy
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static int compareDate(Date date1, Date date2) {
		if (date1.getTime() > date2.getTime()) {
			return 1;
		} else if (date1.getTime() < date2.getTime()) {
			return -1;
		} else {
			return 0;
		}
	}
	
	/**
	 * 两个日期相差的天数
	 * author:sdarmy
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static int getGapOfTwoDate(Date date1,Date date2){
		long day = (date1.getTime()-date2.getTime())/(24*60*60*1000)>0 ? (date1.getTime()-date2.getTime())/(24*60*60*1000):
			   (date2.getTime()-date1.getTime())/(24*60*60*1000);
		return Integer.parseInt(String.valueOf(day));
		
	}
	
	/**
	 * 获取本月最后一天的日子字符串
	 * @return
	 */
	public static String getLastDayThisMonth(String dataFormate){
		Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.roll(Calendar.DAY_OF_MONTH, -1);
        DateFormat format = new SimpleDateFormat(dataFormate); 
		String dateFinal = format.format(cal.getTime()); 	
		return dateFinal;
	}

	/**
	 * 获取当前月第一天的日期字符串
	 * @param dataFormate
	 * @return
	 */
	public static String getFirstDayThisMonth(String dataFormate){
		 Calendar c = Calendar.getInstance();    
	     c.add(Calendar.MONTH, 0);
	     c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天 
	     DateFormat format = new SimpleDateFormat(dataFormate); 
	     String dateFirst = format.format(c.getTime());
	     return dateFirst;
	}
	
	/**
	 * 获取当前月第一天的日期字符串
	 * @param dataFormate
	 * @return
	 */
	public static String getFirstDayNextMonth(String dataFormate){
		 Calendar cal = Calendar.getInstance();
         cal.set(Calendar.DAY_OF_MONTH, 1);
         cal.add(Calendar.MONTH, 1);
	     DateFormat format = new SimpleDateFormat(dataFormate); 
	     String dateFirst = format.format(cal.getTime());
	     return dateFirst;
	}
}


你可能感兴趣的:(java,时间处理)