JAVA日期工具类

JAVA日期工具类

public class DateUtil {
	
    private static final ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<SimpleDateFormat>();  
    
    private static final Object object = new Object();  
    
    /**
     * 得到当前时间 
     * 固定日期格式:yyyy-MM-dd
     * @return
     */
    public static String getDate(){
		SimpleDateFormat ft=new SimpleDateFormat("yyyy-MM-dd");  
		Date dd = new Date();  
		return ft.format(dd); 
	}
    /**
     * 得到当前时间 
     * 固定日期格式:yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String getCurrentTime(){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	return format.format(new Date());
	}
    /**
     * 得到当前时间
     * @param dateType
     * 	 	dateType 如:“yyyy-MM-dd”
     * @return
     */
    public static String getCurrentTime(String dateType){
    	SimpleDateFormat df = new SimpleDateFormat(dateType);//设置日期格式
    	return df.format(new Date());
    }
    /**
     * 得到当前日期为星期几
     * @return
     */
    public static String getDayForWeek(){
    	Date date=new Date();
    	SimpleDateFormat dateFm = new SimpleDateFormat("EEEE");
    	return dateFm.format(date);
    } 
    /**
	 * 转换字符串到日期
	 * @param dateString
	 * @param formatString
	 * @return
	 * @throws ParseException 
	 */
	public static Date convertStringToDate(String dateString) throws ParseException{
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.parse(dateString);
	}

    /** 
     * 将字符串转化为日期。失败返回null。 
     * @param str 日期字符串 
     * @return 日期 
     * 说明:pattern为匹配输入的date格式
     */ 
    public static Date stringToDate(String date, String pattern) {  
        Date myDate = null;  
        if (date != null) {  
            try {
				myDate = getDateFormat(pattern).parse(date);
			} catch (Exception e) {
				Log4jUtil.error(e.getMessage(),e);
			}  
        }  
        return myDate;  
    }
    /** 
     * 将日期转化为日期字符串。失败返回null。 
     * @param date 日期 
     * @return 日期字符串 
     */  
    public static String dateToString(Date date) {
	   SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	   String str = format.format(date);
	   return str;
	} 
    /** 
     * 获取SimpleDateFormat 
     * @param pattern 日期格式 
     * @return SimpleDateFormat对象 
     * @throws RuntimeException 异常:非法日期格式 
     */  
    private static SimpleDateFormat getDateFormat(String pattern) throws RuntimeException {  
        SimpleDateFormat dateFormat = threadLocal.get();  
        if (dateFormat == null) {  
            synchronized (object) {  
                if (dateFormat == null) {  
                    dateFormat = new SimpleDateFormat(pattern);  
                    dateFormat.setLenient(false);  
                    threadLocal.set(dateFormat);  
                }  
            }  
        }  
        dateFormat.applyPattern(pattern);  
        return dateFormat;  
    }  
    /**
     * 得到当前日期处于一年中的第几天
     * @return
     */
    public static int getDayOfYear(){
    	Calendar cal = Calendar.getInstance();//创建一个日期实例
    	cal.setTime(new Date());//实例化一个日期
    	return cal.get(Calendar.DAY_OF_YEAR);
    }
    /**
     * 得到当前周处在一年中的第几周
     * @return
     */
    public static int getWeekOfYear(){
    	Calendar cal = Calendar.getInstance();//创建一个日期实例
    	cal.setTime(new Date());//实例化一个日期
    	return cal.get(Calendar.WEEK_OF_YEAR);
    }
    
    /** 
     * 获取日期的年份。失败返回0。 
     * @param date 日期字符串 
     * @return 年份 
     */  
    public static int getYear(String date, String pattern) {  
        return getYear(stringToDate(date, pattern));  
    }
  
    /** 
     * 获取日期的年份。失败返回0。 
     * @param date 日期 
     * @return 年份 
     */  
    public static int getYear(Date date) {  
        return getInteger(date, Calendar.YEAR);  
    } 
    
    /** 
     * 获取日期的月份。失败返回0。 
     * @param date 日期字符串 
     * @return 月份 
     */  
    public static int getMonth(String date, String pattern) {  
        return getMonth(stringToDate(date, pattern));  
    }
  
    /** 
     * 获取日期的月份。失败返回0。 
     * @param date 日期 
     * @return 月份 
     */  
    public static int getMonth(Date date) {  
        return getInteger(date, Calendar.MONTH) + 1;  
    }  
    
    /** 
     * 获取日期的天数。失败返回0。 
     * @param date 日期字符串 
     * @return 天 
     */  
    public static int getDay(String date, String pattern) {  
        return getDay(stringToDate(date, pattern));  
    } 
  
    /** 
     * 获取日期的天数。失败返回0。 
     * @param date 日期 
     * @return 天 
     */  
    public static int getDay(Date date) {  
        return getInteger(date, Calendar.DATE);  
    }
    
   /** 
    * 获取日期的星期。失败返回null。 
    * @param date 日期 
    * @return 星期 
    */  
    public static  String dayForWeek(String pTime) throws Exception {  
		 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
		 Calendar c = Calendar.getInstance();  
		 c.setTime(format.parse(pTime));  
		 int dayForWeek = 0;  
		 if(c.get(Calendar.DAY_OF_WEEK) == 1){  
		  dayForWeek = 7;  
		 }else{  
		  dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;  
		 }  
		 if(dayForWeek==1){
			 return "周一";
		 }else if(dayForWeek==2){
			 return "周二";
		 }else if(dayForWeek==3){
			 return "周三";
		 }else if(dayForWeek==4){
			 return "周四";
		 }else if(dayForWeek==5){
			 return "周五";
		 }else if(dayForWeek==6){
			 return "周六";
		 }else if(dayForWeek==7){
			 return "周日";
		 }
		 return "";  
	}
    
    /** 
     * 比较两个日期的差值
     * @param date 日期 
     * @param otherDate 另一个日期 
     * @return 相差天数。如果失败则返回-1 
     */  
   public static int daysBetween(Date date,Date otherDate) throws ParseException    
   {    
       SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
       date=sdf.parse(sdf.format(date));  
       otherDate=sdf.parse(sdf.format(otherDate));  
       Calendar cal = Calendar.getInstance();    
       cal.setTime(date);    
       long time1 = cal.getTimeInMillis();                 
       cal.setTime(otherDate);    
       long time2 = cal.getTimeInMillis();         
       long between_days=(time2-time1)/(1000*3600*24);  
           
      return Integer.parseInt(String.valueOf(between_days));           
   } 
   /**
	 * 将两个时间做差运算
	 * @param time1
	 * @param time2
	 * @return
	 */
	 public static long getQuot(String time1, String time2){
		 long quot = 0;
		 SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
		 try {   
			 Date date1 = ft.parse( time1 );   
			 Date date2 = ft.parse( time2 );   
			 quot = date1.getTime() - date2.getTime();   
			 quot = quot / 1000 / 60 / 60 / 24;  
		 } catch (ParseException e) {
			 Log4jUtil.error(e.getMessage(),e);
		 }  
		 return quot; 
	}
   /**
    * 比较两个字符串日期的差值
    * @param date
    * @param otherDate
    * 说明:日期格式必须为 yyyy-MM-dd 或者 yyyy-MM-dd HH:mm:ss
    * @return -1并打印“日期格式不匹配”,则表示差值无效
    * @throws ParseException
    */
   public static int daysBetween(String date,String otherDate) throws ParseException{  
	   // yyyy-MM-dd hh:mm:ss
	   String eL = "^(\\d{4})-([0-1]\\d)-([0-3]\\d)\\s([0-5]\\d):([0-5]\\d):([0-5]\\d)$";
	   Pattern pattern = Pattern.compile(eL);
	   Matcher mDate1 = pattern.matcher(date);
	   boolean dateFlag1 = mDate1.matches();
	   Matcher mOtherDate1 = pattern.matcher(otherDate);
	   boolean otherDateFlag1 = mOtherDate1.matches();
	   // yyyy-MM-dd
	   String eLL = "(19|20)[0-9][0-9]-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[01])";
	   Pattern pattern1 = Pattern.compile(eLL);
	   Matcher mDate2 = pattern1.matcher(date);
	   boolean dateFlag2 = mDate2.matches();
	   Matcher mOtherDate2 = pattern1.matcher(otherDate);
	   boolean otherDateFlag2 = mOtherDate2.matches();
		
	   Calendar cal = Calendar.getInstance();
	   if (dateFlag2 && otherDateFlag2) {
		   cal.setTime(stringToDate(date+" "+"00:00:00","yyyy-MM-dd HH:mm:ss")); 
	       long time1 = cal.getTimeInMillis();                 
	       cal.setTime(stringToDate(otherDate+" "+"00:00:00","yyyy-MM-dd HH:mm:ss"));    
	       long time2 = cal.getTimeInMillis();         
	       long between_days=(time2-time1)/(1000*3600*24);  
	       return Integer.parseInt(String.valueOf(between_days));
		}else if(dateFlag1 && otherDateFlag1){
		       
	       cal.setTime(stringToDate(date,"yyyy-MM-dd HH:mm:ss")); 
	       long time1 = cal.getTimeInMillis();                 
	       cal.setTime(stringToDate(otherDate,"yyyy-MM-dd HH:mm:ss"));    
	       long time2 = cal.getTimeInMillis();         
	       long between_days=(time2-time1)/(1000*3600*24);  
	       return Integer.parseInt(String.valueOf(between_days));
		}else{
			Log4jUtil.error("日期格式不匹配");
			return -1;
		}
   }
   
   /** 
    * 增加日期中某类型的某数值。如增加日期 
    * @param date 日期 
    * @param dateType 类型 
    * @param amount 数值 
    * @return 计算后日期 
    */  
   private static Date addInteger(Date date, int dateType, int amount) {  
       Date myDate = null;  
       if (date != null) {  
           Calendar calendar = Calendar.getInstance();  
           calendar.setTime(date);  
           calendar.add(dateType, amount);  
           myDate = calendar.getTime();  
       }  
       return myDate;  
   } 
   
    /** 
     * 获取日期中的某数值。如获取月份 
     * @param date 日期 
     * @param dateType 日期格式 
     * @return 数值 
     */  
    private static int getInteger(Date date, int dateType) {  
        int num = 0;  
        Calendar calendar = Calendar.getInstance();  
        if (date != null) {  
            calendar.setTime(date);  
            num = calendar.get(dateType);  
        }  
        return num;  
    }  
 
    /** 
     * 增加日期的年份。失败返回null。 
     * @param date 日期 
     * @param yearAmount 增加数量。可为负数 
     * @return 增加年份后的日期 
     */  
    public static Date addYear(Date date, int yearAmount) {  
        return addInteger(date, Calendar.YEAR, yearAmount);  
    }  
  
    /** 
     * 增加日期的月份。失败返回null。 
     * @param date 日期 
     * @param monthAmount 增加数量。可为负数 
     * @return 增加月份后的日期 
     */  
    public static Date addMonth(Date date, int monthAmount) {  
        return addInteger(date, Calendar.MONTH, monthAmount);  
    } 
    
    /** 
     * 增加日期的天数。失败返回null。 
     * @param date 日期 
     * @param dayAmount 增加数量。可为负数 ,负数时即为前几天
     * @return 增加天数后的日期 
     */  
    public static Date addDay(Date date, int dayAmount) {  
        return addInteger(date, Calendar.DATE, dayAmount);  
    }  
  
    /** 
     * 增加日期的小时。失败返回null。 
     * @param date 日期 
     * @param hourAmount 增加数量。可为负数 
     * @return 增加小时后的日期 
     */  
    public static Date addHour(Date date, int hourAmount) {  
        return addInteger(date, Calendar.HOUR_OF_DAY, hourAmount);  
    }  
  
    /** 
     * 增加日期的分钟。失败返回null。 
     * @param date 日期 
     * @param dayAmount 增加数量。可为负数 
     * @return 增加分钟后的日期 
     */  
    public static Date addMinute(Date date, int minuteAmount) {  
        return addInteger(date, Calendar.MINUTE, minuteAmount);  
    }  
  
    /** 
     * 增加日期的秒钟。失败返回null。 
     * @param date 日期 
     * @param dayAmount 增加数量。可为负数 
     * @return 增加秒钟后的日期 
     */  
    public static Date addSecond(Date date, int secondAmount) {  
        return addInteger(date, Calendar.SECOND, secondAmount);  
    }   
    
    /** 
     * oracle时间字符串格式转化。失败返回null。 
     * @param oracleDate oracle数据库获得的日期字符串(timestamp)
     * @return yyyy-MM-dd hh:mm:ss 格式的日期字符串
     */  
    public static String oracleDateToString(String oracleDate) {
    	SimpleDateFormat sdf = new SimpleDateFormat ("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
    	try {
			Date date = sdf.parse(oracleDate);
			String dateString = dateToString(date);
			return dateString;  
		} catch (ParseException e) {
			Log4jUtil.error(e.getMessage(),e);
		}
    	return "";
    }

    /**
     * 获取参数时间和当前时间的差值,去除中间时间的双休日和节假日
     * @param dateTime 参数时间
     * @return 按照常识的时间差(即:分钟,小时,天)
     */
    public static String daysBetweenNowTime(String dateTime) throws ParseException {
        Date target_date = convertStringToDate(dateTime);
        Date current_date = new Date();
        String format = "yyyy-MM-dd hh:mm:ss";
        List yearMonthDayList = new ArrayList();
        //将起止时间中的所有时间加到List中
        Calendar calendarTemp = Calendar.getInstance();
        calendarTemp.setTime(target_date);
        while (calendarTemp.getTime().getTime() <= current_date.getTime()) {
            yearMonthDayList.add(new SimpleDateFormat(format)
                    .format(calendarTemp.getTime()));
            calendarTemp.add(Calendar.DAY_OF_YEAR, 1);
        }
        Collections.sort(yearMonthDayList);
        int num = 0;//周六,周日的总天数
        int size = yearMonthDayList.size();
        int week = 0;
        for (int i = 0; i < size; i++) {
            String day=(String)yearMonthDayList.get(i);
            try {
                calendarTemp.setTime(new SimpleDateFormat(format).parse(day));
            } catch (ParseException e) {
            	Log4jUtil.error(e.getMessage(),e);
            }
            int j = calendarTemp.get(Calendar.DAY_OF_WEEK);
            int value=j-1;//0-星期日
            week = value;
            if (week==6||week==0) {//周六,周日
                num++;
            }
        }
        long between_Sec = current_date.getTime() - target_date.getTime() - num*86400000;
        long days = between_Sec / (1000 * 60 * 60 * 24);
        long hours = (between_Sec % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
        long minutes = (between_Sec % (1000 * 60 * 60)) / (1000 * 60);
        StringBuffer time_buffer = new StringBuffer();
        if(days>1){
            time_buffer.append(days).append("天");
        }
        if(hours>1&&days<7){
            time_buffer.append(hours).append("小时");
        }
        if(minutes>1&&hours<12){
            time_buffer.append(minutes).append("分");
        }
        return time_buffer.toString();
    }
    /**
     * 获取参数时间和当前时间的差值,去除中间时间的双休日和节假日
     * @param dateTime 参数时间
     * @return 按照常识的时间差(即:分钟,小时,天)
     */
    public static String daysBetweenNowTime(String startTime,String endTime) throws ParseException {
    	Date target_date = convertStringToDate(startTime);
    	Date current_date = convertStringToDate(endTime);
    	String format = "yyyy-MM-dd hh:mm:ss";
    	List yearMonthDayList = new ArrayList();
    	//将起止时间中的所有时间加到List中
    	Calendar calendarTemp = Calendar.getInstance();
    	calendarTemp.setTime(target_date);
    	while (calendarTemp.getTime().getTime() <= current_date.getTime()) {
    		yearMonthDayList.add(new SimpleDateFormat(format)
    		.format(calendarTemp.getTime()));
    		calendarTemp.add(Calendar.DAY_OF_YEAR, 1);
    	}
    	Collections.sort(yearMonthDayList);
    	int num = 0;//周六,周日的总天数
    	int size = yearMonthDayList.size();
    	int week = 0;
    	for (int i = 0; i < size; i++) {
    		String day=(String)yearMonthDayList.get(i);
    		try {
    			calendarTemp.setTime(new SimpleDateFormat(format).parse(day));
    		} catch (ParseException e) {
    			Log4jUtil.error(e.getMessage(),e);
    		}
    		int j = calendarTemp.get(Calendar.DAY_OF_WEEK);
    		int value=j-1;//0-星期日
    		week = value;
    		if (week==6||week==0) {//周六,周日
    			num++;
    		}
    	}
    	long between_Sec = current_date.getTime() - target_date.getTime() - num*86400000;
    	long days = between_Sec / (1000 * 60 * 60 * 24);
    	long hours = (between_Sec % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
    	long minutes = (between_Sec % (1000 * 60 * 60)) / (1000 * 60);
    	StringBuffer time_buffer = new StringBuffer();
    	if(days>1){
    		time_buffer.append(days).append("天");
    	}
    	if(hours>1&&days<7){
    		time_buffer.append(hours).append("小时");
    	}
    	if(minutes>1&&hours<12){
    		time_buffer.append(minutes).append("分");
    	}
    	return time_buffer.toString();
    }
    /**
     * 获取参数时间和当前时间的差值,去除中间时间的双休日和节假日
     * @param dateTime 参数时间
     * @param patern 返回差(dd 日期差,hh 小时差  mi 分钟差)
     * @return 按照常识的时间差(即:分钟,小时,天)
     */
    public static String betweenNowTime(String dateTime,String patern) throws ParseException {
    	Date target_date = convertStringToDate(dateTime);
    	//如果target_date是周末,自动加1或者2
    	int nowWeek=0;
    	int addDay=0;
    	nowWeek=getDayAndWeek(target_date);
    	if(nowWeek==6){
    		addDay=2;
    		target_date = addDayTime(target_date,addDay);
    	}else if(nowWeek==0){
    		addDay=1;
    		target_date = addDayTime(target_date,addDay);
    	}
    	Date current_date = new Date();
    	String format = "yyyy-MM-dd hh:mm:ss";
    	List yearMonthDayList = new ArrayList();
    	//将起止时间中的所有时间加到List中
    	Calendar calendarTemp = Calendar.getInstance();
    	calendarTemp.setTime(target_date);
    	while (calendarTemp.getTime().getTime() <= current_date.getTime()) {
    		yearMonthDayList.add(new SimpleDateFormat(format)
    		.format(calendarTemp.getTime()));
    		calendarTemp.add(Calendar.DAY_OF_YEAR, 1);
    	}
    	Collections.sort(yearMonthDayList);
    	int num = 0;//周六,周日的总天数
    	int size = yearMonthDayList.size();
    	int week = 0;
    	for (int i = 0; i < size; i++) {
    		String day=(String)yearMonthDayList.get(i);
    		try {
    			calendarTemp.setTime(new SimpleDateFormat(format).parse(day));
    		} catch (ParseException e) {
    			Log4jUtil.error(e.getMessage(),e);
    		}
    		int j = calendarTemp.get(Calendar.DAY_OF_WEEK);
    		int value=j-1;//0-星期日
    		week = value;
    		if (week==6||week==0) {//周六,周日
    			num++;
    		}
    	}
    	long between_Sec = current_date.getTime() - target_date.getTime() - num*86400000;
    	long days = between_Sec / (1000 * 60 * 60 * 24);
    	long hours = (between_Sec % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
    	long minutes = (between_Sec % (1000 * 60 * 60)) / (1000 * 60);
    	String day="";
    	String hour="";
    	String minute="";
    	String returns="";
    	if(days>0){
    		day=String.valueOf(days)+"天";
    	}
    	if(hours>0){
    		hour=String.valueOf(hours)+"小时";
    	}
    	if(minutes>0){
    		minute=String.valueOf(minutes)+"分钟";
    	}
    	if(patern.equals("dd")){
    		returns = day;
    	}else if(patern.equals("hh")){
    		returns = day+hour;
    	}else if(patern.equals("mi")){
    		returns = day+hour+minute;
    	}
    	if(StringUtil.isEmpty(returns)){
    		returns = "0";
    	}
    	return returns;
    }
    //查看当前日期是否周末
    private static int getDayAndWeek(Date date) throws ParseException{
    	int week = 0;
    	Calendar calendarTemp = Calendar.getInstance();
		calendarTemp.setTime(date);
		int j = calendarTemp.get(Calendar.DAY_OF_WEEK);
		int value=j-1;//0-星期日
		week = value;
    	return week;
    }
    //实现日期相加,时间变成00:00:00
    private static Date addDayTime(Date date,int addDay){
    	 Date myDate = null;  
         if (date != null) {  
             Calendar calendar = Calendar.getInstance();  
             calendar.setTime(date);  
             calendar.add(Calendar.DAY_OF_MONTH, addDay);  
             myDate = calendar.getTime();  
             myDate.setHours(0);
             myDate.setMinutes(0);
             myDate.setSeconds(0);
         }  
         return myDate;  
    }
    /**
     * 获取两个时间的差值,去除中间时间的双休日和节假日
     * @param startTime,endTime 参数时间
     * @param patern 返回差(dd 日期差,hh 小时差  mi 分钟差)
     * @return 按照常识的时间差(即:分钟,小时,天)
     */
    public static String betweenNowTime(String startTime,String endTime,String patern) throws ParseException {
    	Date target_date = convertStringToDate(startTime);
    	Date current_date = convertStringToDate(endTime);
    	String format = "yyyy-MM-dd hh:mm:ss";
    	List yearMonthDayList = new ArrayList();
    	//将起止时间中的所有时间加到List中
    	Calendar calendarTemp = Calendar.getInstance();
    	calendarTemp.setTime(target_date);
    	while (calendarTemp.getTime().getTime() <= current_date.getTime()) {
    		yearMonthDayList.add(new SimpleDateFormat(format)
    		.format(calendarTemp.getTime()));
    		calendarTemp.add(Calendar.DAY_OF_YEAR, 1);
    	}
    	Collections.sort(yearMonthDayList);
    	int num = 0;//周六,周日的总天数
    	int size = yearMonthDayList.size();
    	int week = 0;
    	for (int i = 0; i < size; i++) {
    		String day=(String)yearMonthDayList.get(i);
    		try {
    			calendarTemp.setTime(new SimpleDateFormat(format).parse(day));
    		} catch (ParseException e) {
    			Log4jUtil.error(e.getMessage(),e);
    		}
    		int j = calendarTemp.get(Calendar.DAY_OF_WEEK);
    		int value=j-1;//0-星期日
    		week = value;
    		if (week==6||week==0) {//周六,周日
    			num++;
    		}
    	}
    	long between_Sec = current_date.getTime() - target_date.getTime() - num*86400000;
    	long days = between_Sec / (1000 * 60 * 60 * 24);
    	long hours = (between_Sec % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
    	long minutes = (between_Sec % (1000 * 60 * 60)) / (1000 * 60);
    	if(patern.equals("dd")){
    		return String.valueOf(days);
    	}else if(patern.equals("mi")){
    		return String.valueOf(minutes);
    	}else{
    		//默认都返回小时
    		return String.valueOf(hours);
    	}
    }
    /**
     * 获取参数时间和当前时间的差值,去除中间时间的双休日和节假日
     * @param dateTime 参数时间
     * @return 精确到时分秒的时间差
     */
    public static String timeBetweenTwoTime(String startTime,String endTime) throws ParseException {
    	Date target_date = convertStringToDate(startTime);
    	Date current_date = convertStringToDate(endTime);
    	String format = "yyyy-MM-dd hh:mm:ss";
    	List yearMonthDayList = new ArrayList();
    	//将起止时间中的所有时间加到List中
    	Calendar calendarTemp = Calendar.getInstance();
    	calendarTemp.setTime(target_date);
    	while (calendarTemp.getTime().getTime() <= current_date.getTime()) {
    		yearMonthDayList.add(new SimpleDateFormat(format)
    		.format(calendarTemp.getTime()));
    		calendarTemp.add(Calendar.DAY_OF_YEAR, 1);
    	}
    	Collections.sort(yearMonthDayList);
    	int num = 0;//周六,周日的总天数
    	int size = yearMonthDayList.size();
    	int week = 0;
    	for (int i = 0; i < size; i++) {
    		String day=(String)yearMonthDayList.get(i);
    		try {
    			calendarTemp.setTime(new SimpleDateFormat(format).parse(day));
    		} catch (ParseException e) {
    			Log4jUtil.error(e.getMessage(),e);
    		}
    		int j = calendarTemp.get(Calendar.DAY_OF_WEEK);
    		int value=j-1;//0-星期日
    		week = value;
    		if (week==6||week==0) {//周六,周日
    			num++;
    		}
    	}
    	long between_Sec = current_date.getTime() - target_date.getTime() - num*86400000;
    	long days = between_Sec / (1000 * 60 * 60 * 24);
    	long hours = (between_Sec % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
    	long minutes = (between_Sec % (1000 * 60 * 60)) / (1000 * 60);
    	long sencond = (between_Sec % (1000 * 60 )) / (1000);
    	StringBuffer time_buffer = new StringBuffer();
    	
    	if(hours>1){
    		time_buffer.append(days*24+hours).append("小时");
    	}
    	if(minutes>1&&hours<12){
    		time_buffer.append(minutes).append("分");
    	}
    	if(sencond>=0&&minutes<60){
    		time_buffer.append(sencond).append("秒");
    	}
    	return time_buffer.toString();
    }
    
    /**
     * 比较两个字符串分钟的差值
     * @param date
     * @param otherDate
     * 说明:日期格式必须为yyyy-MM-dd HH:mm:ss
     * @return -1并打印“日期格式不匹配”,则表示差值无效
     * @throws ParseException
     */
    public static int minsBetween(String date,String otherDate) throws ParseException{  
 	   // yyyy-MM-dd hh:mm:ss
 	   String eL = "^(\\d{4})-([0-1]\\d)-([0-3]\\d)\\s([0-5]\\d):([0-5]\\d):([0-5]\\d)$";
 	   Pattern pattern = Pattern.compile(eL);
 	   Matcher mDate1 = pattern.matcher(date);
 	   boolean dateFlag1 = mDate1.matches();
 	   Matcher mOtherDate1 = pattern.matcher(otherDate);
 	   boolean otherDateFlag1 = mOtherDate1.matches();
 	   // yyyy-MM-dd
 	   String eLL = "(19|20)[0-9][0-9]-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[01])";
 	   Pattern pattern1 = Pattern.compile(eLL);
 	   Matcher mDate2 = pattern1.matcher(date);
 	   boolean dateFlag2 = mDate2.matches();
 	   Matcher mOtherDate2 = pattern1.matcher(otherDate);
 	   boolean otherDateFlag2 = mOtherDate2.matches();
 		
 	   Calendar cal = Calendar.getInstance();
 	   if (dateFlag2 && otherDateFlag2) {
 		   cal.setTime(stringToDate(date+" "+"00:00:00","yyyy-MM-dd HH:mm:ss")); 
 	       long time1 = cal.getTimeInMillis();                 
 	       cal.setTime(stringToDate(otherDate+" "+"00:00:00","yyyy-MM-dd HH:mm:ss"));    
 	       long time2 = cal.getTimeInMillis();         
 	       long between_days=(time2-time1)/(1000*60);  
 	       return Integer.parseInt(String.valueOf(between_days));
 		}else if(dateFlag1 && otherDateFlag1){
 		       
 	       cal.setTime(stringToDate(date,"yyyy-MM-dd HH:mm:ss")); 
 	       long time1 = cal.getTimeInMillis();                 
 	       cal.setTime(stringToDate(otherDate,"yyyy-MM-dd HH:mm:ss"));    
 	       long time2 = cal.getTimeInMillis();         
 	       long between_days=(time2-time1)/(1000*60);  
 	       return Integer.parseInt(String.valueOf(between_days));
 		}else{
 			Log4jUtil.error("日期格式不匹配");
 			return -1;
 		}
    }
    /**
     * 获取日期范围内的所有日期集合
     * @param start  起始日期
     * @param end   结束日期
     * @return
     */
    public static List<String> getAllDates(String start,String end){ //
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<String> list = new ArrayList<String>(); //保存日期集合
        try {
            Date date_start = sdf.parse(start);
            Date date_end = sdf.parse(end);
            Date date =date_start;
            Calendar cd = Calendar.getInstance();//用Calendar 进行日期比较判断
            while (date.getTime()<=date_end.getTime()){
                list.add(sdf.format(date));
                cd.setTime(date);
                cd.add(Calendar.DATE, 1);//增加一天 放入集合
                date=cd.getTime();
            }
        } catch (ParseException e) {
            Log4jUtil.error(e.getMessage(), e);
        }
        return list;
    }
    /*
	 * 获取日期之间的所有日期
	 */
	public static  List<String> getDates(String startTime,String endTime){
		List<String> result = null;
		try {
			SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd");
			
			Date dateStart =dateFormat.parse(startTime);
			Calendar calendarStart = Calendar.getInstance();
			calendarStart.setTime(dateStart);
			
			Date dateEnd =dateFormat.parse(endTime);
			Calendar calendarEnd = Calendar.getInstance();
			calendarEnd.setTime(dateEnd);
			
			
			
			result = new ArrayList<String>();
			result.add(startTime);
			calendarStart.add(Calendar.DAY_OF_YEAR, 1);
			while (calendarStart.before(calendarEnd)) {
			    result.add(dateFormat.format(calendarStart.getTime()));
			    calendarStart.add(Calendar.DAY_OF_YEAR, 1);
			}
			result.add(endTime);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    return result;
	}
	
	/*
	 * 检查是否为周末
	 */
	public static boolean checkIsHoliday(String dateTime){
		try {
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");        
			Date date = dateFormat.parse(dateTime); 
			    Calendar cal = Calendar.getInstance();
			    cal.setTime(date);
			    if(cal.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY||
			    		cal.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY){
			    return true;
			 }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
}  



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值