获取两个日期的时间差,可以使用Java中的时间处理类,例如java.util.Date和java.time.LocalDateTime类。下面分别介绍这两种方式的具体实现方法:
- 使用java.util.Date类实现时间差:
代码示例:
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeDifference {
public static void main(String[] args) {
String date1 = "2020-12-01 08:00:00";
String date2 = "2020-12-01 09:30:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date d1 = sdf.parse(date1);
Date d2 = sdf.parse(date2);
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.println("时间差为:" + diffDays + "天" + diffHours + "小时" + diffMinutes + "分钟" + diffSeconds + "秒");
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行结果:
时间差为:0天1小时30分钟0秒
- 使用java.time.LocalDateTime类实现时间差:
代码示例:
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class TimeDifference {
public static void main(String[] args) {
String date1 = "2020-12-01 08:00:00";
String date2 = "2020-12-01 09:30:00";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime ldt1 = LocalDateTime.parse(date1, dtf);
LocalDateTime ldt2 = LocalDateTime.parse(date2, dtf);
Duration dur = Duration.between(ldt1, ldt2);
long diffSeconds = dur.getSeconds() % 60;
long diffMinutes = dur.toMinutes() % 60;
long diffHours = dur.toHours() % 24;
long diffDays = dur.toDays();
System.out.println("时间差为:" + diffDays + "天" + diffHours + "小时" + diffMinutes + "分钟" + diffSeconds + "秒");
}
}
运行结果:
时间差为:0天1小时30分钟0秒
以上就是获取两个日期的时间差的完整攻略了,可以根据自己的需求选择其中一种方法实现。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:java如何获取两个日期的时间差 - Python技术站