您的位置:首页 > 编程语言 > Java开发

Java日期时间处理

2016-01-08 18:34 543 查看
我的Java日期时间处理

最近在公司做统计分析项目,经常碰见需要按天统计,按周统计,按月统计的需要,跟日期时间的处理就必不可少了。鉴于博主自己的水平有限,也对Joda-Time等之类的日期时间处理组件知之甚少,所幸Java自带API中Date和Calendar两个类还比较强大,基本能满足我现在的需求。

贴代码之前,我先讲解一下我的命名规则,以方便各位看官理解,基于方便处理的目的,基本九成以上的方法都是直接返回java.util.Date的结果。再次我也特别提供了dateToString、formatStringDT的转换方法去format Date结果

规则:

1、我的方法都基于见名知意的原则,如果不理解,每个方法,或者每组重载方法都提供了相应的注释
2、用于判断的都用 isXXX 格式,用于取值的都以 getXXX开头
a:getXXXs 之类,为取数量
b:getStartXXX 之类,为按需取开始时间,格式如此例:2015-01-01 00:00:00
c:getEndXXX 之类,为按需取结束时间,格式如此例:2015-12-31 23:59:59

d:getStrXXX 之类,为取字符串格式的时间,默认格式为 yyyy-MM-dd HH:mm:ss
e:getOffSetXXX 之类,为按需取偏移时间
f:rollXXX 之类,为向前或者向后滚动时间
g:CN 和 EN 分别为 符合中文习惯 和 英文习惯的标记
h:DT 是 DateTime 的简写,SE 是 StartEnd 的简写
3、有一个很明显的缺点:如果不是默认格式,拿到结果之后还需要重新format,或者调用传参之前需要预处理 参数的格式以符合默认格式。后期改进。

本人在此贴出代码,一来也是希望对新手有所帮助,二来也希望高手指正,相互学习。在此感谢。下面是代码:
/**
 * 类名称:DateTime
 * 类描述: 日期处理相关
 */
public class DateTime {

	// 年月格式
	public static final String YEAR_MONTH_PATTERN = "yyyy-MM";
	// 日期格式
	public static final String DATE_PATTERN = "yyyy-MM-dd";
	// 时间格式
	public static final String TIME_PATTERN = "HH:mm:ss";
	// 日期时间格式
	public static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
	// 精确日期时间格式
	public static final String EXACT_DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss.SSS";
	
	public static SimpleDateFormat defaultDF = new SimpleDateFormat(DATE_TIME_PATTERN);
	
	public static final String[] CN_WEEK = new String[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
	public static final String[] EN_WEEK = new String[] { "Sunday", "Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday" };
	
	/**
	 * 描述: 获取当前日期
	 */
	public static Date getDate(){
		return new Date();
	}
	public static Date getNow(){
		return getDate();
	}
	public static Date getYesterday(){
		return rollDay(getDate(), -1);
	}
	public static Date getTomorrow(){
		return rollDay(getDate(), 1);
	}
	
	/**
	 * 这种用法规定参数只能是DATE_TIME_PATTERN格式,不然转换报错!
	 */
	public static Date getDate(String dateTime){
		return stringToDate(dateTime);
	}
	
	/**
	 * 描述: 根据 Calendar 的属性获取相应值
	 */
	public static int getField(int typeValue){
		return getField(new Date(), typeValue);
	}
	public static int getYear(){
		return getField(Calendar.YEAR);
	}
	public static int getMonth(){
		return getField(Calendar.MONTH);
	}
	public static int getDay(){
		return getField(Calendar.DAY_OF_MONTH);
	}
	public static int getHour(){
		return getField(Calendar.HOUR);
	}
	public static int getMinute(){
		return getField(Calendar.MINUTE);
	}
	public static int getSecond(){
		return getField(Calendar.SECOND);
	}
	public static int getField(Date date, int typeValue){
		if(null == date){
			date = new Date();
		}
		Calendar cd = Calendar.getInstance();
    	cd.setTime(date);
    	if(typeValue == Calendar.MONTH){
    		return cd.get(typeValue)+1;
    	}else{
    		return cd.get(typeValue);
    	}
	}
	
	/**
	 * 获得指定字符串格式的当前时间
	 */
	public static String getStrCurrentDT(String pattern) {
		if(isNotNull(pattern)){
			return dateToString(new Date(), pattern);
		}else{
			return getStrCurrentDT();
		}
	}
	public static String getStrCurrentDT() {
		return dateToString(new Date(), DATE_TIME_PATTERN);
	}
	
	/**
	 * 判断一个字符串是否是空
	 */
	public static boolean isNotNull(String str) {
		return (null != str && !"".equals(str.trim()) && !"null".equals(str));
	}
	
	/**
	 * 描述: 判断是否是闰年
	 */
	public static boolean isLeapYear(int year) {
		return (((year % 4 == 0 && year % 100 != 0)) || (year % 400 == 0));
	}
	public static boolean isLeapYear(Date date) {
		Calendar cld = Calendar.getInstance();
		if(null == date){
			date = new Date();
		}
		cld.setTime(date);
		int year = cld.get(Calendar.YEAR);
		return (((year % 4 == 0 && year % 100 != 0)) || (year % 400 == 0));
	}
	
	/**
	 * String时间转换成 Date
	 */
	public static Date stringToDate(String time, String pattern){
		SimpleDateFormat sdf = null;
		if(pattern.equals(DATE_TIME_PATTERN)){
			sdf = defaultDF;
		}else{
			sdf = new SimpleDateFormat(pattern);
		}
		Date date = null;
		try {
			date = sdf.parse(time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}
	public static Date stringToDate(String time){
		return stringToDate(time, DATE_TIME_PATTERN);
	}

	/**
	 * Date类型时间转换成 String形式
	 */
	public static String dateToString(Date date, String pattern) {
		return new SimpleDateFormat(pattern).format(date);
	}
	public static String dateToString(Date date) {
		return defaultDF.format(date);
	}
	
	/**
	 * 描述: 将字符串格式的时间做格式转换
	 */
	public static String formatStringDT(String strTime, String oldPattern, String newPattern) {
        SimpleDateFormat getsdf = new SimpleDateFormat(oldPattern);
        SimpleDateFormat resdf = new SimpleDateFormat(newPattern);
        String dateTime = null;
        try {
			 dateTime = resdf.format(getsdf.parse(strTime));
		} catch (ParseException e) {
			e.printStackTrace();
		}
        return dateTime;
    }
	
	/**
	 * 获取当前月份, 字符串形式
	 * @return 返回字符串 格式:两位数
	 */
	public static String getStrCurrentMonth() {
		Calendar cld = Calendar.getInstance();
		int intMon = cld.get(Calendar.MONTH) + 1;
		if (intMon < 10){
			return ("0" + String.valueOf(intMon));
		}else{
			return String.valueOf(intMon);
		}
	}
	
	/**
	 * 描述: 得到某年某月的天数
	 */
	public static int getDaysOfMonth(int year, int month){   
        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8  
                  || month == 10 || month == 12) {   
              return 31;   
        }   
        if (month == 4 || month == 6 || month == 9 || month == 11) {   
              return 30;   
        }   
        if (month == 2) {   
              if (isLeapYear(year)) {   
                  return 29;   
              } else {   
                  return 28;   
              }   
        }   
        return 0;   
	}
	public static int getDaysOfMonth() {
        Calendar cal = Calendar.getInstance();
        return cal.getActualMaximum(Calendar.DATE);
    }
    public static int getDaysOfMonth(Date date) {
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        int dayOfMonth = cal.getActualMaximum(Calendar.DATE);
        return dayOfMonth;
    }
    /**
     * 描述: 得到date该日期所在月有多少天
     */
    public static int getMonthDaysOfDate() {
    	return getMonthDaysOfDate(null);
    }
    public static int getMonthDaysOfDate(Date date) {
    	Calendar cal = Calendar.getInstance();
    	if(null != date){
    		cal.setTime(date);
    	}
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH)+1;
		int days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
		if(isLeapYear(year)){
			days[1] = 29;
		}
		return days[month - 1];
	}
    
    /**
     * 计算指定日期所在年份的总天数
     */
    public static int getDaysOfYear() {
    	Calendar cd = Calendar.getInstance();
        cd.set(Calendar.DAY_OF_YEAR,1);//把日期设为当年第一天   
        cd.roll(Calendar.DAY_OF_YEAR,-1);//把日期回滚一天。   
        return cd.get(Calendar.DAY_OF_YEAR);
    }
    public static int getDaysOfYear(int year) {
    	Calendar cd = Calendar.getInstance();
    	cd.set(Calendar.YEAR, year);
        cd.set(Calendar.DAY_OF_YEAR,1);//把日期设为当年第一天   
        cd.roll(Calendar.DAY_OF_YEAR,-1);//把日期回滚一天。  
        return cd.get(Calendar.DAY_OF_YEAR);
    }
    public static int getDaysOfYear(Date date) {
    	if(null == date){
    		date = new Date();
    	}
    	Calendar cd = Calendar.getInstance();
    	cd.setTime(date);
        cd.set(Calendar.DAY_OF_YEAR,1);//把日期设为当年第一天   
        cd.roll(Calendar.DAY_OF_YEAR,-1);//把日期回滚一天。   
        int MaxYear = cd.get(Calendar.DAY_OF_YEAR);    
        return MaxYear;  
    }
	
	/**
	 * 获取日期
	 * @param timeType 时间类型,譬如:Calendar.DAY_OF_YEAR
	 * @param timenum  时间数字,譬如:-1 昨天,0 今天,1 明天
	 * @return 日期
	 */
	public static Date getOffsetFromNow(int timeType, int timeNum){
		Calendar cld = Calendar.getInstance();
		cld.add(timeType, timeNum);
		return cld.getTime();
	}
	public static Date getOffsetFromDate(Date date, int timeType, int timeNum){
		Calendar cld = Calendar.getInstance();
		cld.setTime(date);
		cld.add(timeType, timeNum);
		return cld.getTime();
	}
	
	/**
	 * 计算从现在开始几天后的时间
	 * @param afterDay
	 * @param dateFormatter 字符串时间格式
	 * @return
	 */
	public static Date getOffsetDaysFromNow(int afterDay) {
		return getOffsetFromNow(Calendar.DATE, afterDay);
	}
	public static Date getOffsetDaysFromDate(Date date, int afterDay) {
		return getOffsetFromDate(date, Calendar.DATE, afterDay);
	}
	
	/**
	 * 描述: 求两个时间之间的秒差(不精确)
	 */
	public static long getSecondsBetween(Date startDate, Date endDate) {
		long startDT = startDate.getTime();
		long endDT = endDate.getTime();
		long seconds = 0;
		if(startDT >= endDT){
			seconds = (int) ((startDT - endDT) / 1000);
		}else{
			seconds = (int) ((endDT - startDT) / 1000);
		}
        return seconds;
    }
	
	/**
	 * 描述: 重置日期
	 */
	public static Date getResetDate(Date date, int year, int month, int dayOfMonth) {
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month-1);
        cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        return cal.getTime();
    }
	
	/**
	 * 描述: 重置时间
	 */
	public static Date getResetTime(Date date, int hour, int minute, int second) {
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        cal.set(Calendar.HOUR_OF_DAY, hour);
        cal.set(Calendar.MINUTE, minute);
        cal.set(Calendar.SECOND, second);
        return cal.getTime();
    }
	
	/**
	 * 描述: 重置日期时间
	 */
	public static Date getResetDT(Date date, int year, int month, int dayOfMonth, int hour, int minute, int second) {
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month-1);
        cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        cal.set(Calendar.HOUR_OF_DAY, hour);
        cal.set(Calendar.MINUTE, minute);
        cal.set(Calendar.SECOND, second);
        return cal.getTime();
    }
	
	/**
	 * 描述: 按照给定参数获取偏移日期
	 */
	public static Date rollDate(Date date, int years, int months, int days) {
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        cal.add(Calendar.YEAR, years);
        cal.add(Calendar.MONTH, months);
        cal.add(Calendar.DAY_OF_MONTH, days);
        return cal.getTime();
    }
	public static Date rollTime(Date date, int hours, int minutes, int seconds) {
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        cal.add(Calendar.HOUR_OF_DAY, hours);
        cal.add(Calendar.MINUTE, minutes);
        cal.add(Calendar.SECOND, seconds);
        return cal.getTime();
    }
	public static Date rollDateTime(Date date, int years, int months, int days, int hours, int minutes, int seconds) {
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        cal.add(Calendar.YEAR, years);
        cal.add(Calendar.MONTH, months);
        cal.add(Calendar.DAY_OF_MONTH, days);
        cal.add(Calendar.HOUR_OF_DAY, hours);
        cal.add(Calendar.MINUTE, minutes);
        cal.add(Calendar.SECOND, seconds);
        return cal.getTime();
    }
	public static Date rollYear(Date date, int years) {
        return rollDate(date, years, 0, 0);
    }
	public static Date rollMonth(Date date, int months) {
        return rollDate(date, 0, months, 0);
    }
	public static Date rollWeek(Date date, int weeks) {
		return rollDateTime(date, 0, 0, weeks*7, 0, 0, 0);
    }
	public static Date rollDay(Date date, int days) {
        return rollDate(date, 0, 0, days);
    }
	public static Date rollHour(Date date, int hours) {
		return rollTime(date, hours, 0, 0);
    }
	public static Date rollMinute(Date date, int minutes) {
		return rollTime(date, 0, minutes, 0);
    }
	public static Date rollSecond(Date date, int seconds) {
		return rollTime(date, 0, 0, seconds);
    }
	
	/**
	 * 描述: 得到 date 的一天开始时间戳
	 */
	public static String getStrStartDTOfDay(){
		return dateToString(getResetTime(new Date(), 0, 0, 0), DATE_TIME_PATTERN);
	}
	public static String getStrStartDTOfDay(Date date){
		return dateToString(getResetTime(date, 0, 0, 0), DATE_TIME_PATTERN);
	}
	public static Date getStartDTOfDay(){
		return getResetTime(new Date(), 0, 0, 0);
	}
	public static Date getStartDTOfDay(Date date){
		return getResetTime(date, 0, 0, 0);
	}
	
	/**
	 * 描述: 得到 date 的一天结束时间戳
	 */
	public static String getStrEndDTOfDay(Date date) {
		return dateToString(getResetTime(date, 23, 59, 59), DATE_TIME_PATTERN);
	}
	public static String getStrEndDTOfDay() {
		return dateToString(getResetTime(new Date(), 23, 59, 59), DATE_TIME_PATTERN);
	}
	public static Date getEndDTOfDay() {
		return getResetTime(new Date(), 23, 59, 59);
	}
	public static Date getEndDTOfDay(Date date) {
		return getResetTime(date, 23, 59, 59);
	}
	
    /**
     * 获取当周第一天的起始时间,例如2014-08-01 00:00:00
     */
    public static Date getStartDTOfWeek() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, 1);
        return getStartDTOfDay(cal.getTime());
    }
    public static Date getStartDTOfWeek(Date date) {
        Calendar cal = Calendar.getInstance();
        if(null == date){
        	return getStartDTOfWeek();
        }
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_WEEK, 1);
        return getStartDTOfDay(cal.getTime());
    }
    
    /**
     * 描述:获取帝国特色的自然周(周一 -> 周日)开始日期时间,即本周的周一
     */
    public static Date getCNStartDTOfWeek() {
    	return getCNStartDTOfWeek(null);
    }
    public static Date getCNStartDTOfWeek(Date date) {
    	Calendar cal = Calendar.getInstance();
    	if(null != date){
    		cal.setTime(date);
    	}
    	if(cal.get(Calendar.DAY_OF_WEEK) == 1){
    		 return rollDay(cal.getTime(), -6);
    	}else{
    		return rollDay(getStartDTOfWeek(cal.getTime()), 1);
    	}
    }
    
    
    /**
     * 获取当周最后一天的起始时间,例如2014-08-07 23:59:59
     */
    public static Date getEndDTOfWeek() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, 7);
        return getEndDTOfDay(cal.getTime());
    }
    public static Date getEndDTOfWeek(Date date) {
        Calendar cal = Calendar.getInstance();
        if(null == date){
        	return getEndDTOfWeek();
        }
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_WEEK, 7);
        return getEndDTOfDay(cal.getTime());
    }
    
    /**
     * 描述:获取帝国特色的自然周(周一 -> 周日)结束日期时间,即本周的周日
     */
    public static Date getCNEndDTOfWeek() {
    	return getCNEndDTOfWeek(null);
    }
    public static Date getCNEndDTOfWeek(Date date) {
    	Calendar cal = Calendar.getInstance();
    	if(null != date){
    		cal.setTime(date);
    	}
    	if(cal.get(Calendar.DAY_OF_WEEK) == 1){
    		 return getEndDTOfDay(cal.getTime());
    	}else{
    		return rollDay(getEndDTOfWeek(cal.getTime()), 1);
    	}
    }
    
    /**
     * 获取当月第一天的起始时间,例如2014-08-01 00:00:00
     */
    public static Date getStartDTOfMonth() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, 1);
        return getStartDTOfDay(cal.getTime());
    }
    public static Date getStartDTOfMonth(Date date) {
        Calendar cal = Calendar.getInstance();
        if(null == date){
        	return getStartDTOfMonth();
        }
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        return getStartDTOfDay(cal.getTime());
    }
    
    /**
     * 获取当月最后一天的结束时间,例如2014-08-31 23:59:59
     */
    public static Date getEndDTOfMonth() {
    	Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, getDaysOfMonth(cal.getTime()));
        return getEndDTOfDay(cal.getTime());
    }
    public static Date getEndDTOfMonth(Date date) {
    	if(null == date){
        	return getEndDTOfMonth();
        }
    	Calendar cal = Calendar.getInstance();
    	cal.setTime(date);
        cal.set(Calendar.DAY_OF_MONTH, getDaysOfMonth(cal.getTime()));
        return getEndDTOfDay(cal.getTime());
    }
    
    /**
     * 获取上个月第一天的起始时间,例如2014-07-01 00:00:00
     */
    public static Date getStartDTOfLastMonth() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, -1);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        return getStartDTOfDay(cal.getTime());
    }
    public static Date getStartDTOfNextMonth() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, 1);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        return getStartDTOfDay(cal.getTime());
    }
    public static Date getStartDTOffsetMonth(int month) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, month);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        return getStartDTOfDay(cal.getTime());
    }
    
    /**
     * 获取上个月最后一天的结束时间,例如2014-07-31 23:59:59
     */
    public static Date getEndDTOfLastMonth() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, -1);
        cal.set(Calendar.DAY_OF_MONTH, getDaysOfMonth(cal.getTime()));
        return getEndDTOfDay(cal.getTime());
    }
    public static Date getEndDTOfNextMonth() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, 1);
        cal.set(Calendar.DAY_OF_MONTH, getDaysOfMonth(cal.getTime()));
        return getEndDTOfDay(cal.getTime());
    }
    public static Date getEndDTOffsetMonth(int month) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, month);
        cal.set(Calendar.DAY_OF_MONTH, getDaysOfMonth(cal.getTime()));
        return getEndDTOfDay(cal.getTime());
    }
    
    /**
     * 获取当前季度第一天的起始时间
     */
    public static Date getStartDTOfQuarter() {
    	return getStartDTOfQuarter(null);
    }
    public static Date getStartDTOfQuarter(Date date) {
        Calendar cal = Calendar.getInstance();
        if(null != date){
        	cal.setTime(date);
        }
        int month = cal.get(Calendar.MONTH);
        if (month < 3) {
            cal.set(Calendar.MONTH, 0);
        } else if (month < 6) {
            cal.set(Calendar.MONTH, 3);
        } else if (month < 9) {
            cal.set(Calendar.MONTH, 6);
        } else {
            cal.set(Calendar.MONTH, 9);
        }
        cal.set(Calendar.DAY_OF_MONTH, 1);
        return getStartDTOfDay(cal.getTime());
    }
    
    /**
     * 获取当前季度最后一天的结束时间
     */
    public static Date getEndDTOfQuarter() {
    	return getEndDTOfQuarter(null);
    }
    public static Date getEndDTOfQuarter(Date date) {
        Calendar cal = Calendar.getInstance();
        if(null != date){
        	cal.setTime(date);
        }
        int month = cal.get(Calendar.MONTH);
        if (month < 3) {
            cal.set(Calendar.MONTH, 2);
        } else if (month < 6) {
            cal.set(Calendar.MONTH, 5);
        } else if (month < 9) {
            cal.set(Calendar.MONTH, 8);
        } else {
            cal.set(Calendar.MONTH, 11);
        }
        cal.set(Calendar.DAY_OF_MONTH, getDaysOfMonth(cal.getTime()));
        return getEndDTOfDay(cal.getTime());
    }
    
    /**
     * 获取当年第一天的开始时间,例如2014-01-01 00:00:00
     */
    public static Date getStartDTOfYear() {
    	Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_YEAR, 1);
        return getStartDTOfDay(cal.getTime());
    }
    public static Date getStartDTOfYear(Date date) {
    	if(null == date){
        	return getStartDTOfYear();
        }
    	Calendar cal = Calendar.getInstance();
    	cal.setTime(date);
        cal.set(Calendar.DAY_OF_YEAR, 1);
        return getStartDTOfDay(cal.getTime());
    }
    
    /**
     * 获取当年最后一天的结束时间,例如2014-12-31 23:59:59
     */
    public static Date getEndDTOfYear() {
    	Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_YEAR, getDaysOfYear(getDate()));
        return getEndDTOfDay(cal.getTime());
    }
    public static Date getEndDTOfYear(Date date) {
    	if(null == date){
        	return getEndDTOfYear();
        }
    	Calendar cal = Calendar.getInstance();
    	cal.setTime(date);
        cal.set(Calendar.DAY_OF_YEAR, getDaysOfYear(date));
        return getEndDTOfDay(cal.getTime());
    }
    
    /**
     * 获取前一个工作日(只指周一 到 周五)
     */
    public static Date getPrevWorkday() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, -1);
        if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            cal.add(Calendar.DAY_OF_MONTH, -2);
        }
        if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
        return getStartDTOfDay(cal.getTime());
    }
    
    /**
     * 获取下一个工作日(只指周一 到 周五)
     */
    public static Date getNextWorkday() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, 1);
        if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
            cal.add(Calendar.DAY_OF_MONTH, 2);
        }
        if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            cal.add(Calendar.DAY_OF_MONTH, 1);
        }
        return getStartDTOfDay(cal.getTime());
    }
    
    /**
     * 获取当前月的工作日列表
     */
    public static List<Date> getWorkDateListOfMonth(){
    	int days = getDaysOfMonth();
    	Date startDateOfMonth = getStartDTOfMonth();
    	List<Date> dateList = new ArrayList<Date>();
    	for(int i=0; i<days; i++){
    		if(isWorkday(startDateOfMonth)){
    			dateList.add(startDateOfMonth);
    		}
    		startDateOfMonth = rollDay(startDateOfMonth, 1);
    	}
    	return dateList;
    }
    public static List<Date> getWorkDateListOfMonth(Date date){
    	return getDaysList(date);
    }
    public static List<Date> getWorkDateListOfMonth(int year, int month){
    	Date date = getResetDate(getDate(), year, month, 1);
    	return getDaysList(date);
    }
    private static List<Date> getDaysList(Date date){
    	int days = getDaysOfMonth(date);
    	Date startDateOfMonth = getStartDTOfMonth(date);
    	List<Date> dateList = new ArrayList<Date>();
    	for(int i=0; i<days; i++){
    		if(isWorkday(startDateOfMonth)){
    			dateList.add(startDateOfMonth);
    		}
    		startDateOfMonth = rollDay(startDateOfMonth, 1);
    	}
    	return dateList;
    }
    
    /**
     * 描述:获取两个日期之间的所有工作日(周一到周五都算)
     */
    public static List<Date> getWorkDateListBetween(Date startDate, Date endDate){
    	startDate = getStartDTOfDay(startDate);
    	List<Date> dateList = new ArrayList<Date>();
    	while(startDate.getTime() <= endDate.getTime()){
    		if(isWorkday(startDate)){
    			dateList.add(startDate);
    		}
    		startDate = rollDay(startDate, 1);
    	}
    	return dateList;
    }
    
    /**
     * 获取当周的第一个工作日
     */
    public static Date getFirstWorkdateOfWeek() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        return getStartDTOfDay(cal.getTime());
    }
    public static Date getFirstWorkdateOfWeek(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        return getStartDTOfDay(cal.getTime());
    }
    
    /**
     * 获取当周的最后一个工作日
     */
    public static Date getLastWorkdateOfWeek() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
        return getStartDTOfDay(cal.getTime());
    }
    public static Date getLastWorkdateOfWeek(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
        return getStartDTOfDay(cal.getTime());
    }
    
    /**
     * 获取当月的第一个工作日
     */
    public static Date getFirstWorkdateOfMonth() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, 1);
        if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
        	return getStartDTOfDay(rollDay(cal.getTime(), 1));
        }else if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY){
        	return getStartDTOfDay(rollDay(cal.getTime(), 2));
        }else{
        	return getStartDTOfDay(cal.getTime());
        }
    }
    public static Date getFirstWorkdateOfMonth(Date date) {
        Calendar cal = Calendar.getInstance();
        if(null == date){
        	return getFirstWorkdateOfMonth();
        }else{
        	cal.setTime(date);
        }
        cal.set(Calendar.DAY_OF_MONTH, 1);
        if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
        	return getStartDTOfDay(rollDay(cal.getTime(), 1));
        }else if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY){
        	return getStartDTOfDay(rollDay(cal.getTime(), 2));
        }else{
        	return getStartDTOfDay(cal.getTime());
        }
    }
    
    /**
     * 获取当月的最后一个工作日
     */
    public static Date getLastWorkdateOfMonth() {
    	Date lastDate = getEndDTOfMonth();
        Calendar cal = Calendar.getInstance();
        cal.setTime(lastDate);
        if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
        	return getStartDTOfDay(rollDay(cal.getTime(), -2));
        }else if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY){
        	return getStartDTOfDay(rollDay(cal.getTime(), -1));
        }else{
        	return getStartDTOfDay(cal.getTime());
        }
    }
    public static Date getLastWorkdateOfMonth(Date date) {
    	Date lastDate = getEndDTOfMonth(date);
        Calendar cal = Calendar.getInstance();
        if(null == date){
        	return getLastWorkdateOfMonth();
        }else{
        	cal.setTime(date);
        }
        cal.setTime(lastDate);
        if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
        	return getStartDTOfDay(rollDay(cal.getTime(), -2));
        }else if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY){
        	return getStartDTOfDay(rollDay(cal.getTime(), -1));
        }else{
        	return getStartDTOfDay(cal.getTime());
        }
    }
    
    /**
     * 判断指定日期是否是工作日
     */
    public static boolean isWorkday(Date date) {
        Calendar cal = Calendar.getInstance();
        if (null != date) {
            cal.setTime(date);
        }
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        return !(dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY);
    }
    
    /**
     * 获取指定日期是星期几(中文形式)
     */
    public static String getChineseDayName(Date date) {
        Calendar cal = Calendar.getInstance();
        if (null != date) {
            cal.setTime(date);
        }
        return CN_WEEK[cal.get(Calendar.DAY_OF_WEEK) - 1];
    }
    
    /**
     * 获取指定日期是星期几(英文形式)
     */
    public static String getEnglishDayName(Date date) {
        Calendar cal = Calendar.getInstance();
        if (null != date) {
            cal.setTime(date);
        }
        return EN_WEEK[cal.get(Calendar.DAY_OF_WEEK) - 1];
    }
    
    /**
     * 获取指定日期距离当前时间的时间差描述(如3小时前、1天前)
     */
    public static String getOffsetDescription(Date date) {
        long seconds = getSecondsBetween(date, new Date());
        if (Math.abs(seconds) < 60) {
            return Math.abs(seconds) + "秒" + (seconds > 0 ? "前" : "后");
        }
        long minutes = seconds / 60;
        if (Math.abs(minutes) < 60) {
            return Math.abs(minutes) + "分钟" + (minutes > 0 ? "前" : "后");
        }
        long hours = minutes / 60;
        if (Math.abs(hours) < 60) {
            return Math.abs(hours) + "小时" + (hours > 0 ? "前" : "后");
        }
        long days = hours / 24;
        if (Math.abs(days) < 7) {
            return Math.abs(days) + "天" + (days > 0 ? "前" : "后");
        }
        long weeks = days / 7;
        if (Math.abs(weeks) < 5) {
            return Math.abs(weeks) + "周" + (weeks > 0 ? "前" : "后");
        }
        long monthes = days / 30;
        if (Math.abs(monthes) < 12) {
            return Math.abs(monthes) + "个月" + (monthes > 0 ? "前" : "后");
        }
        long years = monthes / 12;
        return Math.abs(years) + "年" + (years > 0 ? "前" : "后");
    }
    
    /**
	 * 时间比较  1:date1靠前 		-1:date1靠后
	 */
	public static int compareDate(Date date1, Date date2) {
		if (date2.getTime() > date1.getTime()) {
			return 1;
		} else if (date2.getTime() < date1.getTime()) {
			return -1;
		} else {
			return 0;
		}
	}
	
	/**
	 * 计算该日期的周开始时间和月开始时间是否都在同一个年份内, 在就 返回 true
	 */
	public static boolean isPerfectWeek(Date date){
		Date startDate = getStartDTOfWeek(date);
		Date endDate = getEndDTOfWeek(date);
		int startDateYear = getField(startDate, Calendar.YEAR);
		int endDateYear = getField(endDate, Calendar.YEAR);
		if(startDateYear == endDateYear){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 描述:得到两个日期之间的日期列表
	 */
	public static List<Date> getDateBetween(String startDate, String endDate) {
		Date dateStart = stringToDate(startDate, DATE_TIME_PATTERN);
		Date dateEnd = stringToDate(endDate, DATE_TIME_PATTERN);
		return getDateBetween(dateStart, dateEnd);
	}
	public static List<Date> getDateBetween(String startDate) {
		Date dateStart = stringToDate(startDate, DATE_TIME_PATTERN);
		Date dateEnd = new Date();
		if(dateStart.getTime() <= dateEnd.getTime()){
			return getDateBetween(dateStart, dateEnd);
		}else{
			return getDateBetween(dateEnd, dateStart);
		}
	}
	public static List<Date> getDateBetween(Date startDate, Date endDate) {
		if(startDate.getTime() <= endDate.getTime()){
			List<Date> dateList = new ArrayList<Date>();
			while(startDate.getTime() <= endDate.getTime()){
				dateList.add(getStartDTOfDay(startDate));
				startDate = rollDay(startDate, 1);
			}
			return dateList;
		}else{
			return getDateBetween(endDate, startDate);
		}
	}
	public static List<Date> getDateBetween(Date startDate) {
		return getDateBetween(startDate, getDate());
	}
	
	/**
	 * 描述:得到两个日期之间的周列表
	 * 每一周只存一个时间,第一周存开始时间,中间的数都是每一周的开始时间, 最后一周存的是结束日期
	 * 如果返回结果只有两个时间,如何判断,他们是同一周的开始结束时间,还是不同周的开始结束时间呢。
	 * 暂时还没想好,替换的处理办法是调用 getWeekBetweenWithSE(Date startDate, Date endDate) 方法
	 */
	public static List<Date> getWeekBetween(Date startDate,Date endDate){
		if(startDate.getTime() > endDate.getTime()){
			return getWeekBetween(endDate, startDate);
		}else{
			List<Date> list = new ArrayList<Date>();
			list.add(startDate);
			Date startTime = getStartDTOfWeek(startDate);
			for(Date d = startTime; compareDate(d, endDate) >= 0; d = rollDay(d, 7)){
				if(d != startTime){
					list.add(d);
				}
			}
			if(list.size() == 1){
				list.add(endDate);
			}else{
				list.set(list.size()-1, endDate);
			}
			return list;
		}
	}
	public static List<Date> getCNWeekBetween(Date startDate,Date endDate){
		if(startDate.getTime() > endDate.getTime()){
			return getCNWeekBetween(endDate, startDate);
		}else{
			List<Date> list = new ArrayList<Date>();
			list.add(startDate);
			Date startTime = getCNStartDTOfWeek(startDate);
			for(Date d = startTime; compareDate(d, endDate) >= 0; d = rollDay(d, 7)){
				if(d != startTime){
					list.add(d);
				}
			}
			if(list.size() == 1){
				list.add(endDate);
			}else{
				list.set(list.size()-1, endDate);
			}
			return list;
		}
	}
	
	/**
	 * 描述:getWeekBetween的进化版本
	 * 每周存两个时间,开始时间和结束时间都存
	 */
	public static List<Date> getWeekBetweenWithSE(Date startDate,Date endDate){
		List<Date> dateList = null;
		if(startDate.getTime() > endDate.getTime()){
			dateList = getWeekBetween(endDate, startDate);
		}else{
			dateList = getWeekBetween(startDate, endDate);
		}
		List<Date> resultList = new ArrayList<Date>();
		int size = dateList.size();
		Date firstDate = dateList.get(0);
		Date lastDate = dateList.get(size - 1);
		if(size == 2){
			resultList.add(firstDate);
			Date firstWeekEndDate = getEndDTOfWeek(firstDate);
			if(firstWeekEndDate.getTime() >= lastDate.getTime()){
				resultList.add(lastDate);
			}else{
				resultList.add(firstWeekEndDate);
				resultList.add(getStartDTOfWeek(lastDate));
				resultList.add(lastDate);
			}
		}else{
			for(int i=0; i<size; i++ ){
				if(i == size - 1){	// 最后一个是结束日期
					resultList.add(getStartDTOfWeek(lastDate));
					resultList.add(lastDate);
				}else if(i == 0){
					resultList.add(firstDate);
					resultList.add(getEndDTOfWeek(firstDate));
				}else{
					resultList.add(dateList.get(i));
					resultList.add(getEndDTOfWeek(dateList.get(i)));
				}
			}
		}
		return resultList;
	}
	public static List<Date> getCNWeekBetweenWithSE(Date startDate,Date endDate){
		List<Date> dateList = null;
		if(startDate.getTime() > endDate.getTime()){
			dateList = getCNWeekBetween(endDate, startDate);
		}else{
			dateList = getCNWeekBetween(startDate, endDate);
		}
		List<Date> resultList = new ArrayList<Date>();
		int size = dateList.size();
		Date firstDate = dateList.get(0);
		Date lastDate = dateList.get(size - 1);
		if(size == 2){
			resultList.add(firstDate);
			Date firstWeekEndDate = getCNEndDTOfWeek(firstDate);
			if(firstWeekEndDate.getTime() >= lastDate.getTime()){
				resultList.add(lastDate);
			}else{
				resultList.add(firstWeekEndDate);
				resultList.add(getCNStartDTOfWeek(lastDate));
				resultList.add(lastDate);
			}
		}else{
			for(int i=0; i<size; i++ ){
				if(i == size - 1){	// 最后一个是结束日期
					resultList.add(getCNStartDTOfWeek(lastDate));
					resultList.add(lastDate);
				}else if(i == 0){
					resultList.add(firstDate);
					resultList.add(getCNEndDTOfWeek(firstDate));
				}else{
					resultList.add(dateList.get(i));
					resultList.add(getCNEndDTOfWeek(dateList.get(i)));
				}
			}
		}
		return resultList;
	}
	
	/**
	 * 描述:得到两个日期之间的月份列表
	 */
	public static List<Date> getMonthBetween(Date startDate,Date endDate){
		if(endDate.getTime() < startDate.getTime()){
			return getMonthBetween(endDate, startDate);
		}else{
			Calendar sc = Calendar.getInstance();
			sc.setTime(startDate);
			Calendar ec = Calendar.getInstance();
			ec.setTime(endDate);
			int startYear = sc.get(Calendar.YEAR);
			int startMonth = sc.get(Calendar.MONTH)+1;
			int endYear = ec.get(Calendar.YEAR);
			int endMonth = ec.get(Calendar.MONTH)+1;
			int length = (endYear - startYear)*12 + (endMonth - startMonth) + 1;
			List<Date> list = new ArrayList<Date>();
			for(int i=0; i<length; i++){
				Date date = getStartDTOfMonth(rollMonth(startDate, i));
				list.add(date);
			}
			list.set(0, startDate);
			list.set(list.size() - 1, endDate);
			return list;
		}
	}
	
	/**
	 * 描述:获取带开始和结束时间的月份列表
	 */
	public static List<Date> getMonthBetweenWithSE(Date startDate,Date endDate){
		List<Date> dateList = null;
		if(endDate.getTime() < startDate.getTime()){
			dateList = getMonthBetween(endDate, startDate);
		}else{
			dateList = getMonthBetween(startDate, endDate);
		}
		List<Date> resultList = new ArrayList<Date>();
		int size = dateList.size();
		Date firstDate = dateList.get(0);
		Date lastDate = dateList.get(size - 1);
		if(size == 2){
			resultList.add(firstDate);
			Date firstMonthEndDate = getEndDTOfMonth(firstDate);
			if(firstMonthEndDate.getTime() >= lastDate.getTime()){
				resultList.add(lastDate);
			}else{
				resultList.add(firstMonthEndDate);
				resultList.add(getStartDTOfMonth(lastDate));
				resultList.add(lastDate);
			}
		}else{
			for(int i=0; i<size; i++ ){
				if(i == size - 1){	// 最后一个是结束日期
					resultList.add(getStartDTOfMonth(lastDate));
					resultList.add(lastDate);
				}else if(i == 0){
					resultList.add(firstDate);
					resultList.add(getEndDTOfMonth(firstDate));
				}else{
					resultList.add(dateList.get(i));
					resultList.add(getEndDTOfMonth(dateList.get(i)));
				}
			}
		}
		return resultList;
	}
	
	/**
	 * 描述: 得到过去完整(不包含今月)的12个月
	 */
	public static List<Date> getLastTwelveMonth(){
		Date endDate = getStartDTOfMonth(rollMonth(getDate(), -1));
		Date startDate = getStartDTOfMonth(rollMonth(endDate, -11));
		return getMonthBetween(startDate, endDate);
	}
	public static List<Date> getLastTwelveMonth(Date date){
		Date endDate = getStartDTOfMonth(rollMonth(date, -1));
		Date startDate = getStartDTOfMonth(rollMonth(endDate, -11));
		return getMonthBetween(startDate, endDate);
	}
    
	/**
     * 得到一年中的总周数
     */
    public static int getWeeksOfYear(int year){
    	Calendar cal = Calendar.getInstance();
    	cal.set(Calendar.YEAR, year);
    	Date startDate = getStartDTOfYear(cal.getTime());
    	Date endDate = getEndDTOfYear(cal.getTime());
    	List<Date> dateList = getWeekBetween(startDate, endDate);
    	return dateList.size();
    }
    public static int getWeeksOfYear(Date date){
    	Calendar cal = Calendar.getInstance();
    	cal.setTime(date);
    	Date startDate = getStartDTOfYear(cal.getTime());
    	Date endDate = getEndDTOfYear(cal.getTime());
    	List<Date> dateList = getWeekBetween(startDate, endDate);
    	return dateList.size();
    }
}


欢迎各位大侠拍砖。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: