各種時間轉換幫助類


import org.apache.commons.collections.CollectionUtils;
import org.yaml.snakeyaml.Yaml;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


public class DateUtils {

	public static final String PATTERN_SPECIA = "MM/dd/yyyy";
	public static final String PATTERN_COMMONLY_All = "yyyy-MM-dd HH:mm:ss";
	public static final String PATTERN_COMMONLY_NONE = "yyyy-MM-dd";
	private static final String CRON_DATE_FORMAT = "ss mm HH dd MM ? yyyy";
	public static final String PATTERN_COMMONLY_NUMBER = "yyyyMMdd";
	public static final String PATTERN_COMMONLY_NUMBER_YU = "yyyyMMddHHmmss";
	public static final String PATTERN_COMMONLY_NUMBER_POS = "YYYYMMDDHHMMSS";
	/***
	 *	定時任務 使用的時間表達式
	 * @param date 時間
	 * @return cron類型的日期
	 */
	public static String getCron(final Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat(CRON_DATE_FORMAT);
		String formatTimeStr = "";
		if (date != null) {
			formatTimeStr = sdf.format(date);
		}
		return formatTimeStr;
	}

	public static String format(Long times){
        StringBuilder builder = new StringBuilder();
        if(times!=null){
			long hours = times/(60*60*1000);
			if(hours>0){
			    builder.append(hours).append("h");
            }
            long min = (times%(60*60*1000))/(60*1000);
            long sec = ((times%(60*60*1000))%(60*1000))/1000;
            if(min>0){
                builder.append(min).append("mins");
            }else{
                if(sec>0 && hours>0){
                    builder.append(min).append("mins");
                }
            }
            if(sec>0){
                builder.append(sec).append("s");
            }
		}
		return builder.toString();
	}

	/**
	 * 日期:Date轉String
	 *
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String format(Date date, String pattern) {
		if (date == null || pattern == null) {
			return null;
		}
		SimpleDateFormat dt = new SimpleDateFormat(pattern);
		return dt.format(date);
	}

    /**
     * 日期:String轉Date
     * @param date    日期字符串
     * @param pattern 日期格式
     * @return
     */
    public static Date parse(String date, String pattern) {
        if (date == null || pattern == null) {
            return null;
        }
        Date resultDate = null;
        try {
            resultDate = new SimpleDateFormat(pattern).parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return resultDate;
    }

    /**
     * 日期:特殊格式String轉Date(dd/MM/yyyy)
     * @param date    日期字符串
     * @return
     */
    public static Date parse(String date) {
		String[] datas = date.split("/");
		String newData = datas[2]+"-"+datas[0]+"-"+datas[1]+" 00:00:00";
		Date d = null;
		try {
			d = new SimpleDateFormat(PATTERN_COMMONLY_All).parse(newData);
		} catch (ParseException e) {
			e.printStackTrace();
		}
        return d;
    }

    /**
     * 配合數據庫原有數據方便查詢 去掉時分秒
     * yyyy-MM-dd
     * @param
     * @return
     */
	public static Date change(Date date){
		SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_COMMONLY_NONE);
		//去掉時分秒
		String s=sdf.format(date);
		try {
			date = sdf.parse(s);
		} catch (ParseException e) {
			date = getToday();
		}
		return date;
	}

	/**
	 * 根據當前時間獲得昨天的日期
	 * @return
	 */
	public static Date getYesterday(){
		Date yesterday = getToday();
		Calendar cal = Calendar.getInstance();
		cal.setTime(yesterday);
		cal.add(Calendar.DATE,-1);//日期加1天
		yesterday = cal.getTime();
		return yesterday;
	}

	/**
	 * 根據傳入時間獲得昨天時間
	 * @param date
	 * @return
	 */
	public static Date getYesterday(Date date){
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE,-1);//日期減少1天
		date = cal.getTime();
		return date;
	}

	/**
	 * 根據傳入時間獲得明天時間
	 * @param date
	 * @return
	 */
	public static Date getTomorrow(Date date){
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE,1);//日期增加1天
		date = cal.getTime();
		return date;
	}

	/**
	 * 獲得本週開始時間和結束時間
	 * @return
	 */
    public static List<Date> getThisWeek() {
    	List<Date> listDate = new ArrayList<Date>();
    	Calendar cal = Calendar.getInstance();
    	int weekday = cal.get(8);
    	cal.add(5,-weekday);
    	listDate.add(change(cal.getTime()));//本週開始時間
    	cal.add(5,6);
    	listDate.add(change(cal.getTime()));//本週結束時間
		return listDate;
    }

    /**
     * 獲得上週開始時間和結束時間
     * @return
     */
    public static List<Date> getLastWeek() {
    	List<Date> listDate = new ArrayList<Date>();
    	Calendar cal = Calendar.getInstance();
	    cal.setFirstDayOfWeek(Calendar.MONDAY);//將每週第一天設爲星期一,默認是星期天
	    cal.add(Calendar.DATE, -1*7);
	    cal.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);
    	listDate.add(change(cal.getTime()));//上週開始時間
	    cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
    	listDate.add(change(cal.getTime()));//上週結束時間
		return listDate;
    }

    /**
   	 * 獲得本月開始時間和結束時間
   	 * @return
   	 */
    public static List<Date> getThisMonth() {
    	List<Date> listDate = new ArrayList<Date>();
		Calendar cal = Calendar.getInstance();
       	cal.add(Calendar.MONTH, 0);
       	cal.set(Calendar.DAY_OF_MONTH,1);//設置爲1號,當前日期既爲本月第一天
    	listDate.add(change(cal.getTime()));//本月開始時間
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
    	listDate.add(change(cal.getTime()));//本月結束時間
   		return listDate;
   	}

    /**
	 * 獲得上月開始時間和結束時間
	 * @return
	 */
    public static List<Date> getLastMonth() {
    	List<Date> listDate = new ArrayList<Date>();
    	Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MONTH, -1);
		cal.set(Calendar.DAY_OF_MONTH, 1);
    	listDate.add(change(cal.getTime()));//上月開始時間
	    cal.add(Calendar.MONTH, 1);
		cal.add(Calendar.DATE, -1);
    	listDate.add(change(cal.getTime()));//上月結束時間
		return listDate;
    }

    /**
	 * 根據指定月份獲得第一天和最後一天
	 * @return
	 */
    public static List<Date> getTargetMonth(int month) {
    	List<Date> listDate = new ArrayList<Date>();
    	Calendar cal = Calendar.getInstance();
    	if(month!=0){ //設置月份,'0'表示1月份
    		month--;
    	}
		cal.set(Calendar.MONTH,month);
		cal.set(Calendar.DAY_OF_MONTH, 1);
    	listDate.add(change(cal.getTime()));//開始時間
		cal.add(Calendar.MONTH, 1);
		cal.add(Calendar.DATE, -1);
    	listDate.add(change(cal.getTime()));//開始時間
		return listDate;
    }

    /**
	 * 獲得最近第7天的時間
	 * @return
	 */
    public static Date getSevenDay() {
    	Calendar c = Calendar.getInstance();
    	c.add(Calendar.DATE, - 6);
    	Date monday = c.getTime();
		return change(monday);
    }

	/**
	 * 在指定日期上增加或減少小時數
	 *
	 * @param givenDate 指定日期
	 * @param offset    偏移時間(正整數/負整數)
	 * @return 返回一個運算過後的值
	 */
	public static Date getExpiredHour(Date givenDate, int offset) {
		return getExpiredDate(givenDate, offset, Calendar.HOUR);
	}

	/**
	 * 在指定日期上面加一秒鐘
	 * @param date
	 * @return
	 */
	public static Date addOneSecond(Date date) {
	    Calendar calendar = Calendar.getInstance();
	    calendar.setTime(date);
	    calendar.add(Calendar.SECOND, 1);
	    return calendar.getTime();
	}
	/**
	 * 在指定日期上增加或減少時間
	 *
	 * @param givenDate 指定日期
	 * @param offset    偏移時間(正整數/負整數)
	 * @param type      時間類型
	 * @return Date
	 */
	public static Date getExpiredDate(Date givenDate, int offset, int type) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(givenDate);
		cal.add(type, offset);
		return cal.getTime();
	}

	/**
	 * 在指定日期上增加或減少天數
	 *
	 * @param givenDate 指定日期
	 * @param offset    偏移時間(正整數/負整數)
	 */
	public static Date getExpiredDay(Date givenDate, int offset) {
		return getExpiredDate(givenDate, offset, Calendar.DAY_OF_MONTH);
	}


	/**
	 * yyyy-mm-dd hh:mm:ss字符串驗證
	 * @param data
	 * @return
	 */
//	public static boolean isDate(String data) {
//		if(StringUtils.isNotEmpty(data)){
//			Pattern a=Pattern.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s((([0-1][0-9])|(2?[0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
//			Matcher b=a.matcher(data);
//			if(b.matches()) {
//				return true;
//			} else {
//				return false;
//			}
//		}else{
//			return false;
//		}
//   }

	/**
	 * 獲取當前的北京時間
	 * @return
	 */
	public static Date getToday(){

		TimeZone timeZoneSH = TimeZone.getTimeZone("Asia/Shanghai");
		SimpleDateFormat outputFormat = new SimpleDateFormat(PATTERN_COMMONLY_All, Locale.CHINA);
		outputFormat.setTimeZone(timeZoneSH);
		Date date = new Date(System.currentTimeMillis());
		String time = outputFormat.format(date);
		Date date1 = parse(time, PATTERN_COMMONLY_All);
//
//		long ld = 0;
//		try {
//			 URL url = new URL("https://www.baidu.com/");// 取得資源對象
//	         URLConnection uc;
//			uc = url.openConnection();
//			 uc.connect();// 發出連接
//			 ld = uc.getDate();// 讀取網站日期時間
//		} catch (IOException e) {
//			e.printStackTrace();
//		}// 生成連接對象
//
//         Date date = new Date(ld);// 轉換爲標準時間對象
		return date1;

	}

	/**
	 *
	 * @description:字符串轉爲日期 格式:yyyy-MM-dd HH:mm:ss
	 *
	 * @param source
	 * @return
	 */
	public static Date parseToDate(String source) {
		if (source == null) {
			return null;
		}
		SimpleDateFormat format = new SimpleDateFormat(PATTERN_COMMONLY_All);
		try {
			return format.parse(source);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}


	/**
	 * 時間戳轉換成時間格式
	 * @param timeStamp 時間戳
	 * @return 返回一個時間類型
	 */
	public static Date parseTodateByTimeStamp(String timeStamp){
		//這個是你要轉成後的時間的格式
		SimpleDateFormat sdf=new SimpleDateFormat(PATTERN_COMMONLY_All);
		// 時間戳轉換成時間 接口提供的時間戳默認精確到秒 所以這裏需添加三位精確到毫秒
		String sd = sdf.format(new Date(Long.parseLong(timeStamp+"000")));
		return  parseToDate(sd);
	}


	/**
	 * 將傳入的時間轉成天過後計算時間戳
	 * @param dateTime 時間
	 * @return 返回一個時間類型
	 */
	public static Long parseTimeStampByDate(Date dateTime){
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String format = simpleDateFormat.format(dateTime);
		try {
			Date parse = simpleDateFormat.parse(format);
			return parse.getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 得到現在時間
	 *
	 * @return 字符串 yyyyMMdd
	 */
  public static String getStringToday() {
		   Date currentTime = new Date();
		   SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		   String dateString = formatter.format(currentTime);
		   return dateString;
  }

	/**
	 *  今天是星期幾
	 * @param date 時間
	 * @return
	 */
	public static String getWeekOfDate(Date date) {
		String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (w < 0){
			w = 0;
		}
		return weekDays[w];
	}

	/**
	 *  獲取兩個時間之間的天數之差
	 * @param start 開始時間
	 * @param end 結束時間
	 * @return
	 */
	public static int betweenDays(Long start,Long end){
		Long times=end-start;
		Long days = times/(1000*60*60*24)+1;
		return days.intValue();
	}

	/**
	 *  獲取兩個時間之間的小時數之差
	 * @param start 開始時間
	 * @param end 結束時間
	 * @return
	 */
	public static int betweenHours(Long start,Long end){
		Long times=end-start;
		Long days = times/(1000*60*60);
		Long less = times%(1000*60*60);
		if(less>0){
		    return days.intValue()+1;
        }
		return days.intValue();
	}

    /**
     *  獲取兩個時間段之間的所有時間
     * @param begin 開始時間
     * @param end 結束時間
     * @return
     */
	public static List<String> getBetweenDate(String begin,String end){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		List<String> betweenList = new ArrayList<String>();
		try{
            if(format.parse(begin).getTime()>format.parse(end).getTime()){
                return null;
            }
            end = format.format(format.parse(end));
            Calendar startDay = Calendar.getInstance();
			startDay.setTime(format.parse(begin));
			startDay.add(Calendar.DATE, -1);

			while(true){
				startDay.add(Calendar.DATE, 1);
				Date newDate = startDay.getTime();
				String newend=format.format(newDate);
				betweenList.add(newend);
				if(end.equals(newend)){
					break;
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
		}

		return betweenList;
	}

    /**
     *  獲取兩個時間段之間的所有時間
     * @param begin 開始時間
     * @param end 結束時間
     * @return
     */
    public static List<String> getBetweenDate(Date begin,Date end){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String time1 = format.format(begin);
        String time2 = format.format(end);
        return getBetweenDate(time1,time2);
    }

	/**
	 *  獲取兩個時間之間的天數之差
	 * @param start 開始時間
	 * @param end 結束時間
	 * @return
	 */
	public static int betweenDays(Date start,Date end) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date time1 = format.parse(format.format(start));
        Date time2 = format.parse(format.format(end));
        return betweenDays(time1.getTime(), time2.getTime());
	}

	/**
	 *  獲取兩個時間數組是否有交集
	 * @param time1 開始時間
	 * @param time2 結束時間
	 * @return
	 */
	public static boolean betweenDays(String[] time1,String[] time2) throws ParseException {
		if(time1.length>0 && time1.length==time2.length){
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < time1.length; i++) {
                List<String> betweenDate = getBetweenDate(time1[i], time2[i]);
                if(CollectionUtils.isNotEmpty(betweenDate)){
                    for (int j = i+1; j < time1.length; j++) {
                        String startTime = time1[j];
                        String endTime = time2[j];
                        for (String s : betweenDate) {
                            if(format.parse(s).getTime()==format.parse(startTime).getTime()){
                                return true;
                            }
                            if(format.parse(s).getTime()==format.parse(endTime).getTime()){
                                return true;
                            }
                        }
                    }
                }else{
                    return false;
                }
            }
		}
		return false;
	}

	/**
	 * 計算2個日期之間相差的  相差多少年月日
	 * 比如:2011-02-02 到  2017-03-02 相差 6年,1個月,0天
	 * @param fromDate
	 * @param toDate
	 * @return
	 */
	public static String dayComparePrecise(Date fromDate,Date toDate){
	    if(fromDate!=null && toDate!=null){
            StringBuilder builder = new StringBuilder();
            Calendar  from  =  Calendar.getInstance();
            from.setTime(fromDate);
            Calendar  to  =  Calendar.getInstance();
            to.setTime(toDate);

            int fromYear = from.get(Calendar.YEAR);
            int fromMonth = from.get(Calendar.MONTH);
            int fromDay = from.get(Calendar.DAY_OF_MONTH);

            int toYear = to.get(Calendar.YEAR);
            int toMonth = to.get(Calendar.MONTH);
            int toDay = to.get(Calendar.DAY_OF_MONTH);
            int year = toYear  -  fromYear;
            int month = toMonth  - fromMonth;
            int day = toDay  - fromDay;
            if(day<0){
                month = month-1;
            }
            if(year>0){
                if(month<0){
                    year = year-1;
                    month = 12+month;
                }
                builder.append(year).append("年").append(month).append("個月");
            }else{
                builder.append(month).append("個月");
            }
            return builder.toString();
        }
		return null;
	}

    /**
     * 計算一個日期距離當前多少年,多少月
     * 比如:2011-02-02 到  2017-03-02 相差 6年,1個月,0天
     * @param time
     * @return
     */
    public static String dayComparePrecise(String time){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        if(time==null){
        	return null;
		}
        try {
            Date parse = format.parse(time);
            return dayComparePrecise(parse,new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 計算2個日期之間相差的  相差多少年
     * 比如:2011-02-02 到  2017-03-02 相差 6年,1個月,0天
     * @param fromDate
     * @param toDate
     * @return
     */
    public static Integer yearComparePrecise(Date fromDate,Date toDate){
        if(fromDate!=null && toDate!=null){
            Calendar  from  =  Calendar.getInstance();
            from.setTime(fromDate);
            Calendar  to  =  Calendar.getInstance();
            to.setTime(toDate);

            int fromYear = from.get(Calendar.YEAR);
            int fromMonth = from.get(Calendar.MONTH);
            int fromDay = from.get(Calendar.DAY_OF_MONTH);

            int toYear = to.get(Calendar.YEAR);
            int toMonth = to.get(Calendar.MONTH);
            int toDay = to.get(Calendar.DAY_OF_MONTH);
            int year = toYear  -  fromYear;
            int month = toMonth  - fromMonth;
            int day = toDay  - fromDay;
            if(day<0){
                month = month-1;
            }
            if(month<0){
                year = year-1;
            }
            return year;
        }
        return null;
    }

    /**
     * 計算2個日期之間相差的  相差多少年
     * 比如:2011-02-02 到  2017-03-02 相差 6年,1個月,0天
     * @param time
     * @return
     */
    public static Integer yearComparePrecise(String time){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		if(time==null){
			return null;
		}
        try {
            Date parse = format.parse(time);
            return yearComparePrecise(parse,new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章