各种时间转换帮助类


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;
    }

}

你可能感兴趣的:(工具类)