Java8新的时间API获取时间差值与以前的java.util.Date获取时间差值对比
新的时间API分别为 LocalDate、LocalTime 和 LocalDateTime三个类,位于java.time包下,相比于以前的时间处理方式,在线程安全、时区处理、设计等方面做了优化
想要自己写一个计算时间的小脚本,想尝试一下新的API,问题解决了做一个简单的记录,纯手打(虽然没有几个字)
一、使用Date计算时间差值
/**
* 计算两个时间的差值 使用Date SimpleDateFormat方式
* @throws ParseException
*/
public static void oldFunction() throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH.mm");
Date start = simpleDateFormat.parse("8.56");
Date end = simpleDateFormat.parse("18.56");
long result = end.getTime() - start.getTime();
//如果需要其他单位需要自己转换
System.out.println(result); //36000000 单位是毫秒
}
二、使用LocalTime计算时间差值
/**
* 计算两个时间的差值,使用Java8全新的日期和时间API
*/
public static void newFunction(){
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm");
LocalTime start = LocalTime.parse("08:35", dateTimeFormatter);
LocalTime end = LocalTime.parse("18:35", dateTimeFormatter);
Duration duration = Duration.between(start, end);
System.out.println(duration.toMinutes()); //分钟
System.out.println(duration.toHours()); //小时
System.out.println(duration.toMillis()); //毫秒
}