计算两个Date之间的时间差,基本思路为把Date转换为ms(微秒),然后计算两个微秒时间差。
时间的兑换规则如下:
1s秒 = 1000ms毫秒
1min分种 = 60s秒
1hours小时 = 60min分钟
1day天 = 24hours小时
package com.qiyadeng.date;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDifferentExample
{
public static void main(String[] args) {
//给定时间
//String dateStart = "2013-02-19 09:29:58";
//String dateStop = "2013-02-20 11:31:48";
Scanner sc = new Scanner(System.in);
System.out.print("请输入开始时间:");
String dateStart= sc.nextLine();//获取整行数据包括空格
System.out.print("请输入结束时间:");
String dateStop= sc.nextLine();
//格式化日期格式
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//HH:表示24小时制,hh:表示12小时制
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
//获取开始时间距离结束时间的毫秒数
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60; //秒
long diffMinutes = diff / (60 * 1000) % 60; //分钟
long diffHours = diff / (60 * 60 * 1000) % 24; //小时
long diffDays = diff / (24 * 60 * 60 * 1000); //天
System.out.print("两个时间相差:");
System.out.print(diffDays + " 天, ");
System.out.print(diffHours + " 小时, ");
System.out.print(diffMinutes + " 分钟, ");
System.out.print(diffSeconds + " 秒.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行结果:
两个时间相差:1 天, 2 小时, 1 分钟, 50 秒.