JAVA后台时间各种格式相互转换

public class DateUtil {
	private static final Log log = LogFactory.getLog(DateUtil.class);

	/** 年月日 时分秒模式字符串 */
	public static final String YEAR_MONTH_DAY_HOUR_MINUTE_SECOND_PATTERN = "yyyy-MM-dd HH:mm:ss";

	/** 年月日模式字符串 */
	public static final String YEAR_MONTH_DAY_PATTERN = "yyyy-MM-dd";

	/** 时分秒模式字符串 */
	public static final String HOUR_MINUTE_SECOND_PATTERN = "HH:mm:ss";

	/** 年月日时分模式字符串 */
	public static final String YMDHMS_PATTERN = "yyyy-MM-dd HH:mm";
	/** 年月日时模式字符串 */
	public static final String YMDH_PATTERN = "yyyy-MM-dd HH";
	/**
	 * 获取时间差
	 * 
	 * @param date1
	 * @param date2
	 * @return 小时数
	 */
	public static int getHourDifference(Date before, Date after) {
		if (before != null && after != null) {
			return (int) ((before.getTime() - after.getTime()) / (1000 * 60));
		}
		return 0;
	}
	
	/**
     * 获取时间差 保留小数点后一位有效数字
     * @param date1
     * @param date2
     * @return 小时数
     */
    public static Double getDoubleHourDifference(Date before, Date after){
        Double hour = 0d;
        if(before!=null && after!=null){
            DecimalFormat df = new DecimalFormat("#.0");
            Long l = before.getTime() - after.getTime();
            hour = l.doubleValue()/(1000 * 60 * 60);
            hour = Double.parseDouble(df.format(hour));
        }
        return hour;
    }
    
    /**
     * 获取时间差 
     * @param date1
     * @param date2
     * @return 分
     */
    public static int getMinuteDifference(Date before, Date after){
    	if(before!=null && after!=null){
    		return (int) ((before.getTime() - after.getTime())/(1000 * 60 * 60 * 60)); 
    	}
    	return 0;
    }
    
	/**
	 * 获取当前时间减去xx小时前的时间
	 * 
	 * @param date
	 * @param hour
	 * @return
	 */
	public static Date getDateDifference(int hour) {
		return addHour(new Date(), -hour);
	}

	/**
	 * 根据传入的年、月、日构造日期对象
	 * 
	 * @param year
	 *            年
	 * @param month
	 *            月
	 * @param date
	 *            日
	 * @return 返回根据传入的年、月、日构造的日期对象
	 */
	public static Date getDate(final int year, final int month, final int date) {
		Calendar c = Calendar.getInstance();
		c.set(year + 1900, month, date);
		return c.getTime();
	}

	/**
	 * 根据传入的日期格式化pattern将传入的日期格式化成字符串。
	 * 
	 * @param date
	 *            要格式化的日期对象
	 * @param pattern
	 *            日期格式化pattern
	 * @return 格式化后的日期字符串
	 */
	public static String format(final Date date, final String pattern) {
		DateFormat df = new SimpleDateFormat(pattern);
		return df.format(date);
	}

	/**
	 * 将传入的日期按照默认形势转换成字符串(yyyy-MM-dd)
	 * 
	 * @param date
	 *            要格式化的日期对象
	 * @return 格式化后的日期字符串
	 */
	public static String format(final Date date) {
		return format(date, YEAR_MONTH_DAY_PATTERN);
	}

	/**
	 * 获取(yyyy-MM-dd HH:mm)格式的日期时间
	 * 
	 * @param date
	 *            要格式化的日期对象
	 * @return 格式化后的日期字符串
	 */
	public static String formatDateTime(final Date date) {
		return format(date, YMDHMS_PATTERN);
	}
	/**
	 * 获取(yyyy-MM-dd HH:mm:ss)格式的日期时间
	 * 
	 * @param date
	 *            要格式化的日期对象
	 * @return 格式化后的日期字符串
	 */
	public static String formatLongDateTime(final Date date) {
		return format(date, YEAR_MONTH_DAY_HOUR_MINUTE_SECOND_PATTERN);
	}
	/**
	 * 获取(yyyy-MM-dd HH)格式的日期时间
	 * 
	 * @param date
	 *            要格式化的日期对象
	 * @return 格式化后的日期字符串
	 */
	public static String formatYMDHDateTime(final Date date) {
		return format(date, YMDH_PATTERN);
	}
	/**
	 * 根据传入的日期格式化patter将传入的字符串转换成日期对象
	 * 
	 * @param dateStr
	 *            要转换的字符串
	 * @param pattern
	 *            日期格式化pattern
	 * @return 转换后的日期对象
	 * @throws ParseException
	 *             如果传入的字符串格式不合法
	 */
	public static Date parse(final String dateStr, final String pattern)
			throws ParseException {
		DateFormat df = new SimpleDateFormat(pattern);
		return df.parse(dateStr);
	}

	/**
	 * 将传入的字符串按照默认格式转换为日期对象(yyyy-MM-dd)
	 * 
	 * @param dateStr
	 *            要转换的字符串
	 * @return 转换后的日期对象
	 * @throws ParseException
	 *             如果传入的字符串格式不符合默认格式(如果传入的字符串格式不合法)
	 */
	public static Date parse(final String dateStr) throws ParseException {
		if (dateStr.length() == YEAR_MONTH_DAY_PATTERN.length()) {
			return parse(dateStr + " 00:00:00", YEAR_MONTH_DAY_PATTERN);
		} else if (dateStr.length() == YMDHMS_PATTERN.length()) {
			return parse(dateStr + ":00", YMDHMS_PATTERN);
		} else {
			return parse(dateStr, YEAR_MONTH_DAY_PATTERN);
		}
	}

	/**
	 * 获取指定日期的中文显示名(如:2016年11月23日 星期三)
	 * 
	 * @param d
	 *            日期
	 * @return 中文日期
	 */
	public static String getLocalDate(Date d) {
		String date = "";
		if (d != null) {
			Locale l = new Locale("zh", "CN");
			DateFormat df = DateFormat.getDateInstance(DateFormat.FULL, l);
			try {
				date = df.format(d);
			} catch (Exception e) {
				log.error("日期格式转换出现异常:" + e);
			}
		}
		return date;
	}

	/**
	 * 获取当前日期的中文显示名(如:2016年11月23日 星期三)
	 * 
	 * @return 中文显示名
	 */
	public static String getLocalDate() {
		String date = "";
		Locale l = new Locale("zh", "CN");
		DateFormat df = DateFormat.getDateInstance(DateFormat.FULL, l);
		try {
			date = df.format(new Date());
		} catch (Exception e) {
			log.error("日期格式转换出现异常:" + e);
		}
		return date;
	}

	/**
	 * 获取当前时间的中文显示名(如:下午02时07分00秒)
	 * 
	 * @return 中文显示时间
	 */
	public static String getLocalTime() {
		Locale l = new Locale("zh", "CN");
		DateFormat df = DateFormat.getTimeInstance(DateFormat.LONG, l);
		String time = "";
		try {
			time = df.format(new Date());
		} catch (Exception e) {
			log.error("日期格式转换出现异常:" + e);
		}
		return time;
	}

	/**
	 * 获取指定时间的中文显示名(如:下午02时07分00秒)
	 * 
	 * @param d
	 *            时间
	 * @return 中文时间
	 */
	public static String getLocalTime(Date d) {
		Locale l = new Locale("zh", "CN");
		DateFormat df = DateFormat.getTimeInstance(DateFormat.LONG, l);
		String time = "";
		try {
			time = df.format(d);
		} catch (Exception e) {
			log.error("日期格式转换出现异常:" + e);
		}
		return time;
	}

	/**
	 * 获取指定Date的中文日期与时间(如:2016年11月22日 下午2:07)
	 * 
	 * @param d
	 *            时间
	 * @return 中文日期与时间
	 */
	public static String getLocalDateAndTime(Date d) {
		String dateAndTime = "";
		if (d != null) {
			Locale l = new Locale("zh", "CN");
			DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG,
					DateFormat.SHORT, l);
			try {
				dateAndTime = df.format(d);
			} catch (Exception e) {
				log.error("日期格式转换出现异常:" + e);
			}
		}
		return dateAndTime;
	}

	/**
	 * 将某个日期增加指定年数,并返回结果。如果传入负数,则为减。
	 * 
	 * @param date
	 *            要操作的日期对象
	 * @param ammount
	 *            要增加年的数目
	 * @return 结果日期对象
	 */
	public static Date addYear(final Date date, final int ammount) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.YEAR, ammount);
		return c.getTime();
	}

	/**
	 * 将某个日期增加指定月数,并返回结果。如果传入负数,则为减。
	 * 
	 * @param date
	 *            要操作的日期对象
	 * @param ammount
	 *            要增加月的数目
	 * @return 结果日期对象
	 */
	public static Date addMonth(final Date date, final int ammount) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.MONTH, ammount);
		return c.getTime();
	}

	/**
	 * 将某个日期增加指定天数,并返回结果。如果传入负数,则为减。
	 * 
	 * @param date
	 *            要操作的日期对象
	 * @param ammount
	 *            要增加天的数目
	 * @return 结果日期对象
	 */
	public static Date addDay(final Date date, final int ammount) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.DATE, ammount);
		return c.getTime();
	}

	/**
	 * 将某个日期增加指定小时数,并返回结果。如果传入负数,则为减。
	 * 
	 * @param date
	 *            要操作的日期对象
	 * @param hour
	 *            要增加天的小时数
	 * @return 结果日期对象
	 */
	public static Date addHour(final Date date, final int hour) {
		Calendar nowDate = Calendar.getInstance();
		nowDate.add(Calendar.HOUR, hour);
		Date agoDate = (Date) nowDate.getTime();
		return agoDate;
	}

	/**
	 * 将某个日期增加指定分钟数,并返回结果。如果传入负数,则为减。
	 * 
	 * @param date
	 *            要操作的日期对象
	 * @param minute
	 *            要增加的分钟数
	 * @return 结果日期对象
	 */
	public static Date addMinute(final Date date, final int minute) {
		Calendar nowDate = Calendar.getInstance();
		nowDate.add(Calendar.MINUTE, minute);
		Date agoDate = (Date) nowDate.getTime();
		return agoDate;
	}
	/**
	 * 返回给定的beforeDate比afterDate早的年数。如果beforeDate晚于afterDate,则 返回负数。
	 * 
	 * @param beforeDate
	 *            要比较的早的日期
	 * @param afterDate
	 *            要比较的晚的日期
	 * @return beforeDate比afterDate早的年数,负数表示晚。
	 */
	public static int beforeYears(final Date beforeDate, final Date afterDate) {
		Calendar beforeCalendar = Calendar.getInstance();
		beforeCalendar.setTime(beforeDate);
		beforeCalendar.set(Calendar.MONTH, 1);
		beforeCalendar.set(Calendar.DATE, 1);
		beforeCalendar.set(Calendar.HOUR, 0);
		beforeCalendar.set(Calendar.SECOND, 0);
		beforeCalendar.set(Calendar.MINUTE, 0);
		Calendar afterCalendar = Calendar.getInstance();
		afterCalendar.setTime(afterDate);
		afterCalendar.set(Calendar.MONTH, 1);
		afterCalendar.set(Calendar.DATE, 1);
		afterCalendar.set(Calendar.HOUR, 0);
		afterCalendar.set(Calendar.SECOND, 0);
		afterCalendar.set(Calendar.MINUTE, 0);
		boolean positive = true;
		if (beforeDate.after(afterDate))
			positive = false;
		int beforeYears = 0;
		while (true) {
			boolean yearEqual = beforeCalendar.get(Calendar.YEAR) == afterCalendar
					.get(Calendar.YEAR);
			if (yearEqual) {
				break;
			} else {
				if (positive) {
					beforeYears++;
					beforeCalendar.add(Calendar.YEAR, 1);
				} else {
					beforeYears--;
					beforeCalendar.add(Calendar.YEAR, -1);
				}
			}
		}
		return beforeYears;
	}

	/**
	 * 返回给定的beforeDate比afterDate早的月数。如果beforeDate晚于afterDate,则 返回负数。
	 * 
	 * @param beforeDate
	 *            要比较的早的日期
	 * @param afterDate
	 *            要比较的晚的日期
	 * @return beforeDate比afterDate早的月数,负数表示晚。
	 */
	public static int beforeMonths(final Date beforeDate, final Date afterDate) {
		Calendar beforeCalendar = Calendar.getInstance();
		beforeCalendar.setTime(beforeDate);
		beforeCalendar.set(Calendar.DATE, 1);
		beforeCalendar.set(Calendar.HOUR, 0);
		beforeCalendar.set(Calendar.SECOND, 0);
		beforeCalendar.set(Calendar.MINUTE, 0);
		Calendar afterCalendar = Calendar.getInstance();
		afterCalendar.setTime(afterDate);
		afterCalendar.set(Calendar.DATE, 1);
		afterCalendar.set(Calendar.HOUR, 0);
		afterCalendar.set(Calendar.SECOND, 0);
		afterCalendar.set(Calendar.MINUTE, 0);
		boolean positive = true;
		if (beforeDate.after(afterDate))
			positive = false;
		int beforeMonths = 0;
		while (true) {
			boolean yearEqual = beforeCalendar.get(Calendar.YEAR) == afterCalendar
					.get(Calendar.YEAR);
			boolean monthEqual = beforeCalendar.get(Calendar.MONTH) == afterCalendar
					.get(Calendar.MONTH);
			if (yearEqual && monthEqual) {
				break;
			} else {
				if (positive) {
					beforeMonths++;
					beforeCalendar.add(Calendar.MONTH, 1);
				} else {
					beforeMonths--;
					beforeCalendar.add(Calendar.MONTH, -1);
				}
			}
		}
		return beforeMonths;
	}

	/**
	 * 返回给定的beforeDate比afterDate早的天数。如果beforeDate晚于afterDate,则 返回负数。
	 * 
	 * @param beforeDate
	 *            要比较的早的日期
	 * @param afterDate
	 *            要比较的晚的日期
	 * @return beforeDate比afterDate早的天数,负数表示晚。
	 */
	public static int beforeDays(final Date beforeDate, final Date afterDate) {
		Calendar beforeCalendar = Calendar.getInstance();
		beforeCalendar.setTime(beforeDate);
		beforeCalendar.set(Calendar.HOUR, 0);
		beforeCalendar.set(Calendar.SECOND, 0);
		beforeCalendar.set(Calendar.MINUTE, 0);
		Calendar afterCalendar = Calendar.getInstance();
		afterCalendar.setTime(afterDate);
		afterCalendar.set(Calendar.HOUR, 0);
		afterCalendar.set(Calendar.SECOND, 0);
		afterCalendar.set(Calendar.MINUTE, 0);
		boolean positive = true;
		if (beforeDate.after(afterDate))
			positive = false;
		int beforeDays = 0;
		while (true) {
			boolean yearEqual = beforeCalendar.get(Calendar.YEAR) == afterCalendar
					.get(Calendar.YEAR);
			boolean monthEqual = beforeCalendar.get(Calendar.MONTH) == afterCalendar
					.get(Calendar.MONTH);
			boolean dayEqual = beforeCalendar.get(Calendar.DATE) == afterCalendar
					.get(Calendar.DATE);
			if (yearEqual && monthEqual && dayEqual) {
				break;
			} else {
				if (positive) {
					beforeDays++;
					beforeCalendar.add(Calendar.DATE, 1);
				} else {
					beforeDays--;
					beforeCalendar.add(Calendar.DATE, -1);
				}
			}
		}
		return beforeDays;
	}

	/**
	 * 返回传人日期是星期几:周日是0、周一是1...周六是6
	 * 
	 * @param date
	 * @return
	 */
	public static int getDayOfWeek(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.get(Calendar.DAY_OF_WEEK) - 1;
	}

	/**
	 * 获取给定日期对象的年
	 * 
	 * @param date
	 *            日期对象
	 * @return 年
	 */
	public static int getYear(final Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.get(Calendar.YEAR);
	}

	/**
	 * 获取给定日期对象的月
	 * 
	 * @param date
	 *            日期对象
	 * @return 月
	 */
	public static int getMonth(final Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.get(Calendar.MONTH) + 1;
	}

	/**
	 * 获取给定日期对象的天
	 * 
	 * @param date
	 *            日期对象
	 * @return 天
	 */
	public static int getDay(final Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.get(Calendar.DATE);
	}

	/**
	 * 获取给定日期对象的时
	 * 
	 * @param date
	 *            日期对象
	 * @return 时
	 */
	public static int getHour(final Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.get(Calendar.HOUR_OF_DAY);
	}

	/**
	 * 获取给定日期对象的分
	 * 
	 * @param date
	 *            日期对象
	 * @return 分
	 */
	public static int getMinute(final Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.get(Calendar.MINUTE);
	}

	/**
	 * 获取给定日期对象的秒
	 * 
	 * @param date
	 *            日期对象
	 * @return 秒
	 */
	public static int getSecond(final Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.get(Calendar.SECOND);
	}

	/**
	 * 计算两个时间相隔的天数小时和分【两个时间顺序无影响】
	 * 
	 * @param befor
	 *            时间参数 1 格式:yyyy-MM-dd HH:mm:ss
	 * @param after
	 *            时间参数 2 格式:yyyy-MM-dd HH:mm:ss
	 * @return long[] 返回值为:{天, 时, 分}
	 */
	public static long[] getDistanceDayHourMin(Date befor,Date after) {
		long day = 0;
		long hour = 0;
		long min = 0;
		try {
			long time1 = befor.getTime();
			long time2 = after.getTime();
			long diff;
			if (time1 < time2) {
				diff = time2 - time1;
			} else {
				diff = time1 - time2;
			}
			day = diff / (24 * 60 * 60 * 1000);
			hour = (diff / (60 * 60 * 1000) - day * 24);
			min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		long[] dhm = { day, hour, min };
		return dhm;
	}
	
	/**
	 * 
	* @Title: getDistanceDay 
	* @Description: 计算两个时间 共持续的天数
	* @param @param befor
	* @param @param after
	* @param @return    设定文件 
	* @return long    返回类型 
	* @author heweihui
	* @throws
	 */
	public static long getDistanceDay(Date befor,Date after) {
        long day = 0;
        try {
            long time1 = befor.getTime();
            long time2 = after.getTime();
            long diff;
            if (time1 < time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            day = diff / (24 * 60 * 60 * 1000) + 1;
            /*if(diff != 0){
            }*/
        } catch (Exception e) {
            log.error(e.getLocalizedMessage(), e);
        }
        return day;
    }
	
	/**
     * 
    * @Title: getStartDate 
    * @Description: 获取给定日期 增加ammount天 零点的日期  传入正数则为增加,传入负数则为减去
    * @param @param date 日期
    * @param @param ammount 天数 
    * @param @return    设定文件 
    * @return Date    日期
    * @author heweihui
    * @throws
     */
    public static Date getStartDate(final Date date, final int ammount){
        Calendar c = Calendar.getInstance();
        c.setTime(addDay(date,ammount));
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return c.getTime();
    }
    
    /**
     * 
    * @Title: getEndDate 
    * @Description: 获取给定日期 增加ammount天 末点的日期  传入正数则为增加,传入负数则为减去
    * @param @param date
    * @param @param ammount
    * @param @return    设定文件 
    * @return Date    日期
    * @author heweihui
    * @throws
     */
    public static Date getEndDate(final Date date, final int ammount){
        Calendar c = Calendar.getInstance();
        c.setTime(addDay(date,ammount));
        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.MINUTE, 59);
        c.set(Calendar.SECOND, 59);
        c.set(Calendar.MILLISECOND, 999);
        return c.getTime();
    }

	@Test
	public void test() throws ParseException {
//		System.out.println(getDistanceDayHourMin(
//				parse("2016-12-09 03:23:00",
//						YEAR_MONTH_DAY_HOUR_MINUTE_SECOND_PATTERN),
//				parse("2016-12-07 22:23:00",
//						YEAR_MONTH_DAY_HOUR_MINUTE_SECOND_PATTERN)));
		/*List<String> list =new ArrayList<String>();
		list.add("1");
		list.add("2");
		list.add("3");
		list.add("4");
		list.add("5");
		list.add("6");
		int s=0;int l=2;
		int e=s*l+l;
		List<String> list1= list.subList(s*2, e);
		s++;e=s*l+l;
		List<String> list11= list.subList(s*2, e);	
		s++;e=s*l+l;
		List<String> list12= list.subList(s*2, e);
		s++;e=s*l+l;
		//List<String> list13= list.subList(s*2, e);
		
		System.out.println(getStartDate(new Date(),-2));*/
	    
	    /*Date date = new Date();
	    Date date1 = addDay(date, -1);
	    System.out.println(format(date));
	    System.out.println(format(date1));
	    
	    int a = beforeDays(date1, date);
	    long b = getDistanceDay(date1, date);
	    System.out.println(a);
	    System.out.println(b);*/
	    /*Long day = DateUtil.getDistanceDay(DateUtil.parse("2016-12-26"), DateUtil.parse("2016-12-27"));
	    System.out.println(day);*/
	    /*Double b = 7.88890;
	    BigDecimal decimal = new BigDecimal(b);  
        decimal = decimal.setScale(0, RoundingMode.HALF_UP);  
        System.out.println(decimal);*/
	    /*Dictionary dictionary = new Dictionary();
	    dictionary.setDictp((byte) 9);
        //if (dictp == dictionary.getDictp()) {
	    String a = "omo.xls";
	    String[] b = a.split("\\.");
	    System.out.println(b.length);*/
	    String a = ",1188,1191,10375,10376";
	    System.out.println(a.substring(1));
	    String path = SystemParam.getProperties("APP_MAINTAIN_REPORT_PATH");
	    System.out.println(path);
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值