public static void main(String[] args) throws ParseException {
String StringTime1 = "2018-08-13 12:20:30";
String StringTime2 = "2018-08-13 12:20:31";
String differenceFormat = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//yyyy-mm-dd, 会出现时间不对, 因为小写的mm是代表: 秒
Date dateTime1 = sdf.parse(StringTime1);
Date dateTime2 = sdf.parse(StringTime2);
long difference = dateTime1.getTime() - dateTime2.getTime();
System.out.println("相差毫秒数:"+difference);
long days = difference / (1000 * 60 * 60 * 24);
long hours = (difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
long minutes = (difference % (1000 * 60 * 60)) / (1000 * 60);
long seconds = (difference % (1000 * 60)) / 1000;
differenceFormat = days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds ";
System.out.println("相差时间:"+differenceFormat);
}
比较两个string类型的日期 并输出时间差
Java日期时间差计算
最新推荐文章于 2023-12-12 18:31:32 发布
本文介绍了一种使用Java计算两个日期时间之间差值的方法,包括毫秒数、天数、小时数、分钟数和秒数的计算。通过解析字符串格式的日期时间,转换为Date类型,然后计算两个日期之间的差值。
1496

被折叠的 条评论
为什么被折叠?



