日期格式转换工具类

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

public class DateUtil {
	
	public static String FORMAT_yyyy_MM_dd_HH_mm_ss = "yyyy-MM-dd HH:mm:ss";
	public static String FORMAT_yyyy_MM_dd_HH_mm = "yyyy-MM-dd HH:mm";
	public static String FORMAT_yyyy_MM_dd = "yyyy-MM-dd";
	public static String FORMAT_yyyy_MM = "yyyy-MM";
	public static String FORMAT_MM = "MM";
	public static String FORMAT_dd = "dd";
	public static String FORMAT_yyyy = "yyyy";
	public static String FORMAT_yyyyMMddHHmmss = "yyyyMMddHHmmss";
	public static String FORMAT_yyyyMMdd = "yyyyMMdd";
	public static String FORMAT_yyyy_MM_dd_HH = "yyyy-MM-dd HH";
	public static String FORMAT_yyMMdd = "yyMMdd";
	public static String FORMAT_HH_mm_ss = "HH:mm:ss";
	public static String FORMAT_HHmmss = "HHmmss";
	
	public static final void main(String[] args) {
		System.out.println(stringToDate("20180101"));
	}
	
	public static Date getdate(int i) // //获取前后日期 i为正数 向后推迟i天,负数时向前提前i天
	 {
		 Date dat = null;
		 Calendar cd = Calendar.getInstance();
		 cd.add(Calendar.DATE, i);
		 dat = cd.getTime();
		 SimpleDateFormat dformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 Timestamp date = Timestamp.valueOf(dformat.format(dat));
		 return date;
	 }
	
	public static String convertDateToString(Date date, String format) {
		if (date != null) {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			return sdf.format(date);
		}
		
		return null;
	}
	public static Date convertStringToDate(String dateString, String format) {
		Date date = null;
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			if (!StringUtil.isBlank(dateString)) {
				date = sdf.parse(dateString);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}
	public static Date convertTackOutPoint(Date date){
		if(null == date){
			return null;
		}
		Timestamp timestamp=new Timestamp(date.getTime());
		String timeStr=timestamp.toString().substring(0, timestamp.toString().indexOf("."));
		return convertStringToDate(timeStr,DateUtil.FORMAT_yyyy_MM_dd_HH_mm_ss);
	}


	/**
	 * 字符串转换为日期:不支持yyM[M]d[d]格式
	 * 
	 * @param date
	 * @return
	 */
	public static final Date stringToDate(String date) {
		if (date == null) {
			return null;
		}
		String separator = String.valueOf(date.charAt(4));
		String pattern = "yyyyMMdd";
		if (!separator.matches("\\d*")) {
			pattern = "yyyy" + separator + "MM" + separator + "dd";
			if (date.length() < 10) {
				pattern = "yyyy" + separator + "M" + separator + "d";
			}
		} else if (date.length() < 8) {
			pattern = "yyyyMd";
		}
		pattern += " HH:mm:ss.SSS";
		pattern = pattern.substring(0, Math.min(pattern.length(), date.length()));
		try {
			return new SimpleDateFormat(pattern).parse(date);
		} catch (ParseException e) {
			return null;
		}
	}
	/**
     * nDay为推迟的周数,1本周,-1向前推迟一周,2下周...
     * weekDay星期几, sunday=0, monday=1...saturday=6
     */
    public static String getCalDatebyWeek(int nDay, int weekDay){
    	Calendar cal = Calendar.getInstance();
    	cal.add(Calendar.DATE, nDay*7);
    	
    	cal.set(Calendar.DAY_OF_WEEK, weekDay);//eg:Calendar.MONDAY
    	return DateUtil.convertDateToString(cal.getTime(), DateUtil.FORMAT_yyyy_MM_dd);
    }
    public static String[] getLastMonthEndDate(Date date, int nMon){
    	Calendar cal = Calendar.getInstance();
    	if(date != null){
    		cal.setTime(date);
    	}
    	cal.add(Calendar.MONTH, nMon);
    	int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    	
    	cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), 1, 00, 00, 00);
    	String startDate = DateUtil.convertDateToString(cal.getTime(), DateUtil.FORMAT_yyyy_MM_dd_HH_mm_ss);
    	cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), maxDay, 23, 59, 59);
    	String endDate = DateUtil.convertDateToString(cal.getTime(), DateUtil.FORMAT_yyyy_MM_dd_HH_mm_ss);
    	return new String[]{startDate, endDate};
    }
    
    public static String getLastByDay(int day){
    	Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, day);//eg:-30
		return DateUtil.convertDateToString(calendar.getTime(), DateUtil.FORMAT_yyyy_MM_dd);
    }
    
	public String converLongToDate(Long ms) {
	    Date date = new Date(ms);
	    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	    String time = format.format(date);
		return time;
	}
	
	
	/**
	 * 2日期时间差
	 */
	public static long getDatesLag(String subtrahendStr, Date minuend){
		return (DateUtil.convertStringToDate(subtrahendStr, DateUtil.FORMAT_yyyy_MM_dd_HH_mm_ss).getTime()-minuend.getTime());
	}
	
	public static long getDatesLag(Date fdate, Date minuend){
		return (fdate.getTime()-minuend.getTime());
	}
	
	public static int getDatesLag(String subtrahendStr, String endStr){
		Long time = (DateUtil.convertStringToDate(subtrahendStr, DateUtil.FORMAT_yyyy_MM_dd_HH_mm_ss).getTime()-DateUtil.convertStringToDate(endStr, DateUtil.FORMAT_yyyy_MM_dd_HH_mm_ss).getTime());
		Long days = time / (1000 * 60 * 60 * 24);
		return days.intValue();
	}
	public static int getDatesDays(String subtrahendStr, String endStr){
		Long time = (DateUtil.convertStringToDate(subtrahendStr, DateUtil.FORMAT_yyyy_MM_dd).getTime()-DateUtil.convertStringToDate(endStr, DateUtil.FORMAT_yyyy_MM_dd).getTime());
		Long days = time / (1000 * 60 * 60 * 24);
		return days.intValue();
	}
	
	/**
	 * 是否在指定时间之间
	 */
	public static boolean isInDatesLag(String startDate, String endDate, Date now){
		if(getDatesLag(startDate, now)<0 && getDatesLag(endDate, now)>0){
			return true;
		}
		return false;
	}
	
	public static boolean isToday(Date date) { 
	    Calendar c1 = Calendar.getInstance();              
	    c1.setTime(date);                                 
	    int year1 = c1.get(Calendar.YEAR);
	        int month1 = c1.get(Calendar.MONTH)+1;
	        int day1 = c1.get(Calendar.DAY_OF_MONTH);     
	        Calendar c2 = Calendar.getInstance();    
	        c2.setTime(new Date());      
	        int year2 = c2.get(Calendar.YEAR);
	        int month2 = c2.get(Calendar.MONTH)+1;
	        int day2 = c2.get(Calendar.DAY_OF_MONTH);   
	        if(year1 == year2 && month1 == month2 && day1 == day2){
	        return true;
	        }
	    return false;                               
	}
	
	public static boolean isBeforeDate(String compareDate, Date now){
		return now.before(DateUtil.convertStringToDate(compareDate, DateUtil.FORMAT_yyyy_MM_dd_HH_mm_ss));
		//return getDatesLag(compareDate, now)>0?true:false;
	}
	
	public static boolean isBeforeDate(String compareDate, String format, Date now){
		return now.before(DateUtil.convertStringToDate(compareDate, format));
		//return getDatesLag(compareDate, now)>0?true:false;
	}
	
	public static boolean isAfterDate(String compareDate, Date now){
		return now.after(DateUtil.convertStringToDate(compareDate, DateUtil.FORMAT_yyyy_MM_dd_HH_mm_ss));
		//return getDatesLag(compareDate, now)<0?true:false;
	}
	public static boolean isAfterDate(String compareDate, String format, Date now){
		return now.after(DateUtil.convertStringToDate(compareDate, format));
		//return getDatesLag(compareDate, now)<0?true:false;
	}
	
	public static boolean isBeforeDate(String compareDate, Date now, int second){
		return getDatesLag(compareDate, now)>-second*1000?true:false;
	}
	public static boolean isAfterDate(String compareDate, Date now, int second){
		return getDatesLag(compareDate, now)<-second*1000?true:false;
	}
	public static boolean isSameWeek(String compareDate, Date now){
		Calendar cal1 = Calendar.getInstance();
		Calendar cal2 = Calendar.getInstance();
		cal1.setTime(DateUtil.convertStringToDate(compareDate, DateUtil.FORMAT_yyyy_MM_dd));
		cal2.setTime(now);
		if(cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR)){
			return true;
		}
		return false;
	}
	
	
	
	public static Date getDateAfterTime(String dateStr, int second) {
		Date date = DateUtil.convertStringToDate(dateStr, DateUtil.FORMAT_yyyy_MM_dd_HH_mm_ss);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.SECOND, calendar.get(Calendar.SECOND) + second);
		
		return calendar.getTime();
	}
	public static Date getDateAfterDates(Date date, int dates) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + dates);
		
		return calendar.getTime();
	}
	
	public static Date getDateAfterHours(Date date, int hours) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) + hours);
		return calendar.getTime();
	}
	
	/**
	 * @Title getDateBeforeDates 
	 * @Description 获取比时间晚N天的时间
	 * @param date
	 * @param dates
	 * @return
	 */
	public static Date getDateBeforeDates(Date date, int dates) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - dates);
		
		return calendar.getTime();
	}
	
	public static Date getDateAfterMonths(Date date, int months) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + months);
		
		return calendar.getTime();
	}
	public static String removeMs(String dateStr){
		if(!StringUtil.isBlank(dateStr)){
			int i = dateStr.indexOf(".");
			if(i > -1){
				dateStr = dateStr.substring(0, i);
			}
		}
		return dateStr;
	}
	/**
	 * 0=sunday
	 */
	public static int getWeekDay(Date date){
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		int weekDay = cal.get(Calendar.DAY_OF_WEEK);
		weekDay = weekDay - 1;
		return weekDay;
	}
	/**
	 * 返回两个日期间的差异天数
	 * 
	 * @param date1 大
	 * @param date2  小
	 * @return 如:5秒,20分钟,1小时51分钟,2天4小时,大于1个月(参照日期与比较日期之间的天数差异,正数表示参照日期在比较日期之后,0表示两个日期同天,负数表示参照日期在比较日期之前)
	 */
	public static String dayDiff3(Date date1, Date date2) {
		long diff = date1.getTime() - date2.getTime();
		if(diff <= 0){
			return "今日已结束";
		}
		diff = diff / 1000;
		if(diff / 60 == 0){
			return "还有"+(diff % 60) + "秒钟结束";
		}else if(diff / 3600 == 0){
			return "还有"+(diff % 3600 / 60) + "分钟结束";
		}else if(diff / (3600 * 24) == 0){
			int h = (int) (diff / 3600 );
			int m = (int) ((diff % 3600) / 60);
			return "还有"+h + "小时" + m + "分钟结束";
		}else if(diff / (3600 * 24) < 30){
			int d = (int) (diff / (3600 * 24));
			int h = (int) (diff % (3600 * 24) / 3600 );
			return "还有"+d + "天" + h + "小时结束";
		}else{
			return "还有"+"1个月以上结束";
		}
	}
	/**
	 * 获取日期所在月份的最后一天
	 */
	public static Date getMonthLastDay(Date date){
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));  
		return cal.getTime();
	}
	/**
	 * 获取日期所在月份的第一天
	 */
	public static Date getMonthFirstDay(Date date){
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.set(Calendar.DATE, cal.getActualMinimum(Calendar.DATE));  
		return cal.getTime();
	}
	/**
	 * 获取自然上月的最后一天
	 */
	public static Date getNextMonthLastDay(Date date){
		Calendar calendar = Calendar.getInstance();
		int month = calendar.get(Calendar.MONTH);
		calendar.set(Calendar.MONTH, month-1);
		calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH));  
		return calendar.getTime();
	}
	/**
	 * 获取自然上月的第一天
	 */
	public static Date getNextMonthFirstDay(Date date){
		Calendar calendar = Calendar.getInstance();
		int month = calendar.get(Calendar.MONTH);
		calendar.set(Calendar.MONTH, month-1);
		calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMinimum(Calendar.DAY_OF_MONTH));  
		return calendar.getTime();
	}
	
	
	/**
	 * 2日期时间差
	 */
	public static long getDateSecond(String endDate, String startDate){
		return (DateUtil.convertStringToDate(endDate, DateUtil.FORMAT_yyyy_MM_dd_HH_mm_ss).getTime()
				- DateUtil.convertStringToDate(startDate, DateUtil.FORMAT_yyyy_MM_dd_HH_mm_ss).getTime())/1000;
	}
	
	/**
	 * 减掉多少小时
	 */
	public static String addDate(String day, int x) 
	   { 
	        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");//24小时制 
	        //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//12小时制 
	        Date date = null; 
	        try 
	        { 
	            date = format.parse(day); 
	        } 
	        catch (Exception ex)    
	        { 
	            ex.printStackTrace(); 
	        } 
	        if (date == null) return ""; 
	        Calendar cal = Calendar.getInstance(); 
	        cal.setTime(date); 
	        cal.add(Calendar.HOUR_OF_DAY, x);//24小时制 
	        //cal.add(Calendar.HOUR, x);12小时制 
	        date = cal.getTime(); 
	        //System.out.println("front:" + date); 
	        cal = null; 
	        return format.format(date); 
	  } 
	
	public static String addDateMinut(String day, int x)//返回的是字符串型的时间,输入的
	//是String day, int x
	 {   
	        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");// 24小时制  
	//引号里面个格式也可以是 HH:mm:ss或者HH:mm等等,很随意的,不过在主函数调用时,要和输入的变
	//量day格式一致
	        Date date = null;   
	        try {   
	            date = format.parse(day);   
	        } catch (Exception ex) {   
	            ex.printStackTrace();   
	        }   
	        if (date == null)   
	            return "";   
	        //System.out.println("front:" + format.format(date)); //显示输入的日期  
	        Calendar cal = Calendar.getInstance();   
	        cal.setTime(date);   
	        cal.add(Calendar.MINUTE, x);// 24小时制   
	        date = cal.getTime();   
	        //System.out.println("after:" + format.format(date));  //显示更新后的日期 
	        cal = null;   
	        return format.format(date);   
	  
	    } 
	
	/**
	 * @Title daysBetween 
	 * @Description 计算两个日期之间相差的天数
	 * @param smdate
	 * @param bdate
	 * @return
	 * @throws ParseException
	 */
	public static int daysBetween(Date smdate,Date bdate) throws ParseException 
	{    
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
        smdate=sdf.parse(sdf.format(smdate));  
        bdate=sdf.parse(sdf.format(bdate));  
        Calendar cal = Calendar.getInstance();    
        cal.setTime(smdate);    
        long time1 = cal.getTimeInMillis();                 
        cal.setTime(bdate);    
        long time2 = cal.getTimeInMillis();         
        long between_days=(time2-time1)/(1000*3600*24);  
            
       return Integer.parseInt(String.valueOf(between_days));           
    } 

	//增加(减少天数) n
	 public static String addDay(String s, int n) {   
	        try {   
	            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");   
	  
	            Calendar cd = Calendar.getInstance();   
	            cd.setTime(sdf.parse(s));   
	            cd.add(Calendar.DATE, n);//增加一天   
	            //cd.add(Calendar.MONTH, n);//增加一个月   
	  
	            return sdf.format(cd.getTime());   
	  
	        } catch (Exception e) {   
	            return null;   
	        }   
	  
	    }   
	 
	//增加(减少天数) n
		 public static String addMonth(String s, int n) {   
		        try {   
		            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");   
		  
		            Calendar cd = Calendar.getInstance();   
		            cd.setTime(sdf.parse(s));   
		            cd.add(Calendar.MONTH, n);//增加一天   
		            //cd.add(Calendar.MONTH, n);//增加一个月   
		  
		            return sdf.format(cd.getTime());   
		  
		        } catch (Exception e) {   
		            return null;   
		        }   
		  
		    }   
		 
		 
		 public static String addMonthFormat(String s, int n,String format) {   
		        try {   
		            SimpleDateFormat sdf = new SimpleDateFormat(format);   
		  
		            Calendar cd = Calendar.getInstance();   
		            cd.setTime(sdf.parse(s));   
		            cd.add(Calendar.MONTH, n);//增加一天   
		            //cd.add(Calendar.MONTH, n);//增加一个月   
		  
		            return sdf.format(cd.getTime());   
		  
		        } catch (Exception e) {   
		            return null;   
		        }   
		  
		    }   
	
	// 获取当前时间所在年的周数
    public static int getWeekOfYear(Date date) {
        Calendar c = new GregorianCalendar();
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setMinimalDaysInFirstWeek(7);
        c.setTime(date);
 
        return c.get(Calendar.WEEK_OF_YEAR);
    }
 
    // 获取当前时间所在年的最大周数
    public static int getMaxWeekNumOfYear(int year) {
        Calendar c = new GregorianCalendar();
        c.set(year, Calendar.DECEMBER, 31, 23, 59, 59);
 
        return getWeekOfYear(c.getTime());
    }
 
    // 获取某年的第几周的开始日期
    public static Date getFirstDayOfWeek(int year, int week) {
        Calendar c = new GregorianCalendar();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, Calendar.JANUARY);
        c.set(Calendar.DATE, 1);
 
        Calendar cal = (GregorianCalendar) c.clone();
        cal.add(Calendar.DATE, week * 7);
 
        return getFirstDayOfWeek(cal.getTime());
    }
 
    // 获取某年的第几周的结束日期
    public static Date getLastDayOfWeek(int year, int week) {
        Calendar c = new GregorianCalendar();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, Calendar.JANUARY);
        c.set(Calendar.DATE, 1);
 
        Calendar cal = (GregorianCalendar) c.clone();
        cal.add(Calendar.DATE, week * 7);
 
        return getLastDayOfWeek(cal.getTime());
    }
 
    // 获取当前时间所在周的开始日期
    public static Date getFirstDayOfWeek(Date date) {
        Calendar c = new GregorianCalendar();
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setTime(date);
        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
        return c.getTime();
    }
 
    // 获取当前时间所在周的结束日期
    public static Date getLastDayOfWeek(Date date) {
        Calendar c = new GregorianCalendar();
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setTime(date);
        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sunday
        return c.getTime();
    }
    
    public static List<WeekVo> getWeeks(Integer year) {
    	List<WeekVo> weeks = new ArrayList<WeekVo>();
    	Date today = new Date();
    	if (null == year) {
    		year = today.getYear();
    	}
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.FORMAT_yyyy_MM_dd);
        
        Calendar c = new GregorianCalendar();
        c.setTime(today);
        int weekNums = getMaxWeekNumOfYear(year);
        for (int i=1;i<=weekNums;i++) {
        	WeekVo vo = new WeekVo();
        	vo.setWeekNum(i);
        	vo.setFirstDayOfWeek(sdf.format(getFirstDayOfWeek(year, i)));
        	vo.setLastDayOfWeek(sdf.format(getLastDayOfWeek(year, i)));
        	weeks.add(vo);
        }
        return weeks;
    }
    
    public static WeekVo getWeekDays(Integer year, Integer weekNum) {
    	WeekVo vo = new WeekVo();
    	Date firstDayOfWeek = DateUtil.getFirstDayOfWeek(year, weekNum);
    	Date lastDayOfWeek = DateUtil.getLastDayOfWeek(year, weekNum);
    	vo.setYear(year);
    	vo.setWeekNum(weekNum);
    	vo.setFirstDayOfWeek(DateUtil.convertDateToString(firstDayOfWeek, DateUtil.FORMAT_yyyy_MM_dd));
    	vo.setLastDayOfWeek(DateUtil.convertDateToString(lastDayOfWeek, DateUtil.FORMAT_yyyy_MM_dd));
    	return vo;
    }
    
    /**
     * @Title getWeekDate 
     * @Description 根据当前年和周数 查询一周的时间
     * @param year
     * @param weekNum
     * @return
     */
    public static List<Date> getWeekDate(Integer year, Integer weekNum) {
    	List<Date> weeks = new ArrayList<Date>();
    	Date today = new Date();
    	if (null == year) {
    		year = today.getYear();
    	}
        Calendar c = new GregorianCalendar();
        c.setTime(today);
        Date day = getFirstDayOfWeek(year, weekNum);
        weeks.add(day);
        for (int i=1;i<7;i++) {
        	day = DateUtil.getSpecifiedDayAfter(day);
        	weeks.add(day);
        }
        return weeks;
    }
    
    /** 
    * 获得指定日期的后一天 
    * @param date 
    * @return 
    * @throws Exception 
    */ 
    public static Date getSpecifiedDayAfter(Date date){ 
    	Calendar c = Calendar.getInstance(); 
    	c.setTime(date); 
    	int day=c.get(Calendar.DATE); 
    	c.set(Calendar.DATE,day+1); 
    	return c.getTime(); 
    } 
    
    /**
     * @Title getMonthNumber 
     * @Description 获取一年中的月号
     * @return
     */
    public static List<Integer> getMonthNumber() {
    	List<Integer> months = new ArrayList<Integer>();
    	for (int i=1; i<=12; i++) {
    		months.add(i);
    	}
    	return months;
    }
    
    /**
     * @Title getDayNumber 
     * @Description 获取一个月的天
     * @return
     */
    public static List<Integer> getDayNumber() {
    	List<Integer> days = new ArrayList<Integer>();
    	for (int i=1; i<=31; i++) {
    		days.add(i);
    	}
    	return days;
    }
    
    /**
     * @Title getWeekNumber 
     * @Description 获取一个星期的天
     * @return
     */
    public static List<Integer> getWeekNumber() {
    	List<Integer> weeks = new ArrayList<Integer>();
    	for (int i=1; i<=7; i++) {
    		weeks.add(i);
    	}
    	return weeks;
    }
    
    /**
     * @Title getHourNumber 
     * @Description 获取小时数组
     * @return
     */
    public static List<Integer> getHourNumber() {
    	List<Integer> hours = new ArrayList<Integer>();
    	for (Integer i=1; i<=24; i++) {
    		hours.add(i);
    	}
    	return hours;
    }
    
    /**
     * 获取当前日期是星期几<br>
     * 
     * @param dt
     * @return 当前日期是星期几
     */
    public static int getWeekOfDate(Date dt) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK)-1;
        if (w==0) {
        	w=7;
        }
        return w;
    }
 
    public static String getWeekStartEnd(){
       	String str = "";
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
//        Calendar lastDate = Calendar.getInstance();
//        lastDate.roll(Calendar.DATE, -6);//日期回滚7天
//        str=sdf.format(lastDate.getTime());
    	Calendar lastDate= Calendar.getInstance();
    	lastDate.setTime(new Date());
    	lastDate.add(lastDate.DAY_OF_YEAR, -6);
    	str=sdf.format(lastDate.getTime());
        return str;
    }
    
    /**
	 * 时间date1和date2的时间差-单位小时
	 *
	 * @param date1
	 * @param date2
	 * @return 小时
	 */
	public static int subtractHour(Date date1, Date date2) {
		long cha = (date2.getTime() - date1.getTime()) / 1000;
		return (int) cha / (60 * 60);
	}
	
	// 注意SimpleDateFormat不是线程安全的
		private static ThreadLocal<SimpleDateFormat> ThreadDateTime = new ThreadLocal<SimpleDateFormat>();
		private static ThreadLocal<SimpleDateFormat> ThreadDate = new ThreadLocal<SimpleDateFormat>();
		private static ThreadLocal<SimpleDateFormat> ThreadTime = new ThreadLocal<SimpleDateFormat>();

		private static SimpleDateFormat DateTimeInstance() {
			SimpleDateFormat df = ThreadDateTime.get();
			if (df == null) {
				df = new SimpleDateFormat(DateUtil.FORMAT_yyyy_MM_dd_HH_mm_ss);
				ThreadDateTime.set(df);
			}
			return df;
		}

		private static SimpleDateFormat DateInstance() {
			SimpleDateFormat df = ThreadDate.get();
			if (df == null) {
				df = new SimpleDateFormat(DateUtil.FORMAT_yyyy_MM_dd);
				ThreadDate.set(df);
			}
			return df;
		}

		private static SimpleDateFormat TimeInstance() {
			SimpleDateFormat df = ThreadTime.get();
			if (df == null) {
				df = new SimpleDateFormat(DateUtil.FORMAT_HH_mm_ss);
				ThreadTime.set(df);
			}
			return df;
		}

	/**
	 * 时间date1和date2的时间差-单位小时
	 *
	 * @param date1
	 * @param date2
	 * @return 小时
	 */
	public static int subtractHour(String date1, String date2) {
		int rs = 0;
		try {
			Date start = DateTimeInstance().parse(date1);
			Date end = DateTimeInstance().parse(date2);
			long cha = (end.getTime() - start.getTime()) / 1000;
			rs = (int) cha / (60 * 60);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return rs;
	}
	
	/**
	 * 根据单位字段比较两个日期
	 * 
	 * @param date
	 *            日期1
	 * @param otherDate
	 *            日期2
	 * @param withUnit
	 *            单位字段,从Calendar field取值
	 * @return 等于返回0值, 大于返回大于0的值 小于返回小于0的值
	 */
	public static int compareDate(Date date, Date otherDate, int withUnit) {
		if(date==null && otherDate==null){
			return 0;
		}
		if(date==null && otherDate != null){
			return -1;
		}
		if(date != null && otherDate == null){
			return 1;
		}
		Calendar dateCal = Calendar.getInstance();
		dateCal.setTime(date);
		Calendar otherDateCal = Calendar.getInstance();
		otherDateCal.setTime(otherDate);

		switch (withUnit) {
		case Calendar.YEAR:
			dateCal.clear(Calendar.MONTH);
			otherDateCal.clear(Calendar.MONTH);
		case Calendar.MONTH:
			dateCal.set(Calendar.DATE, 1);
			otherDateCal.set(Calendar.DATE, 1);
		case Calendar.DATE:
			dateCal.set(Calendar.HOUR_OF_DAY, 0);
			otherDateCal.set(Calendar.HOUR_OF_DAY, 0);
		case Calendar.HOUR:
			dateCal.clear(Calendar.MINUTE);
			otherDateCal.clear(Calendar.MINUTE);
		case Calendar.MINUTE:
			dateCal.clear(Calendar.SECOND);
			otherDateCal.clear(Calendar.SECOND);
		case Calendar.SECOND:
			dateCal.clear(Calendar.MILLISECOND);
			otherDateCal.clear(Calendar.MILLISECOND);
		case Calendar.MILLISECOND:
			break;
		default:
			throw new IllegalArgumentException("withUnit 单位字段 " + withUnit + " 不合法!!");
		}
		return dateCal.compareTo(otherDateCal);
	}
	
	public static int compareTime(Date date, Date otherDate, int withUnit) {
		if(date==null && otherDate==null){
			return 0;
		}
		if(date==null && otherDate != null){
			return -1;
		}
		if(date != null && otherDate == null){
			return 1;
		}
		Calendar dateCal = Calendar.getInstance();
		dateCal.setTime(date);
		Calendar otherDateCal = Calendar.getInstance();
		otherDateCal.setTime(otherDate);

		dateCal.clear(Calendar.YEAR);
		dateCal.clear(Calendar.MONTH);
		dateCal.set(Calendar.DATE, 1);
		otherDateCal.clear(Calendar.YEAR);
		otherDateCal.clear(Calendar.MONTH);
		otherDateCal.set(Calendar.DATE, 1);
		switch (withUnit) {
		case Calendar.HOUR:
			dateCal.clear(Calendar.MINUTE);
			otherDateCal.clear(Calendar.MINUTE);
		case Calendar.MINUTE:
			dateCal.clear(Calendar.SECOND);
			otherDateCal.clear(Calendar.SECOND);
		case Calendar.SECOND:
			dateCal.clear(Calendar.MILLISECOND);
			otherDateCal.clear(Calendar.MILLISECOND);
		case Calendar.MILLISECOND:
			break;
		default:
			throw new IllegalArgumentException("withUnit 单位字段 " + withUnit + " 不合法!!");
		}
		return dateCal.compareTo(otherDateCal);
	}
	
	/**
	 * 将分钟数转换成X天 Xh Xmin的格式
	 *
	 * @param num 分钟数
	 * @return String
	 */
	public static String convertMinToStr(long num) {
		long minute = 0;
		long hour = 0;
		long day = 0;

		if (num > 0) {
			minute = num % 60;
			num -= minute;
			if (num > 0) {
				num /= 60;
				hour = num % 24;
				num -= hour;
				if (num > 0) {
					day = num / 24;
				}
			}
		}

		if (day > 0) {
			return day + "天" + hour + "h" + minute + "min";
		} else if (hour > 0) {
			return hour + "h" + minute + "min";
		} else {
			return minute + "min";
		}
	}
 
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值