欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java代码计算2个时间差,精确到 天、月、日、时、分、秒、毫秒

程序员文章站 2022-03-26 21:12:21
...
/**
	 * 两个时间相差距离多少天多少小时多少分多少秒
	 * @param str1 时间参数 1 格式:2016-06-22 18:21:20
	 * @param str2 时间参数 2 格式:2016-06-22 17:21:20
	 * @param pattern 日期格式 yyyy-MM-dd HH:mm:ss    毫秒(yyyy-MM-dd HH:mm:ss.SSS)
	 * @return String 返回值为:xx天xx小时xx分xx秒
	 */
	public static String getDistanceTime(String str1, String str2, String pattern) {
		DateFormat df = new SimpleDateFormat(pattern);
		Date one;
		Date two;
		long day = 0;
		long hour = 0;
		long min = 0;
		long sec = 0;
		long ms = 0;
		try {
			one = df.parse(str1);
			two = df.parse(str2);
			long time1 = one.getTime();
			long time2 = two.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);
			sec = (diff/1000-day*24*60*60-hour*60*60-min*60);
			//ms = (diff - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000 - min * 60 * 1000 - sec * 1000);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return day + "天" + hour + "小时" + min + "分" + sec + "秒";
		//return day + "天" + hour + "小时" + min + "分" + sec + "秒" + ms + "毫秒";
	}