java中计算两个时间差
不多说,直接上代码,可自行查看示例
package org.example.calc;import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;public class MinusTest {public static void main(String[] args) {// 假设有两个修改时间,格式为yyyy-MM-dd HH:mm:ssString time1 = "2024-05-01 12:00:00";String time2 = "2024-05-02 15:30:00";// 将字符串转换为LocalDateTime对象LocalDateTime dateTime1 = LocalDateTime.parse(time1, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));LocalDateTime dateTime2 = LocalDateTime.parse(time2, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));// 计算两个时间的分钟差异long minutesDiff = ChronoUnit.MINUTES.between(dateTime1, dateTime2);System.out.println("两个时间相差 " + minutesDiff + " 分钟。");// 计算两个时间的秒差异long secondDiff = ChronoUnit.SECONDS.between(dateTime1, dateTime2);System.out.println("两个时间相差 " + secondDiff + " 秒。");// 计算两个时间的小时差异long hourDiff = ChronoUnit.HOURS.between(dateTime1, dateTime2);System.out.println("两个时间相差 " + hourDiff + " 小时。");// 计算两个时间的天数差异long dayDiff = ChronoUnit.DAYS.between(dateTime1, dateTime2);System.out.println("两个时间相差 " + dayDiff + " 天。");//计算时间相加并比较小时差异,此外还可以进行,秒数、分钟、小时、天、月和年的相加LocalDateTime localDateTime = ChronoUnit.HOURS.addTo(dateTime1, 5);long between = ChronoUnit.HOURS.between(localDateTime, dateTime2);System.out.println("两个时间相差 " + between + " 小时。");}
}
运行结果如下图所示:
话说,这个JDK自带的时间计算还是挺好用的,大家觉得呢?
拓展:时间戳格式化为日期
Long currentTimeMillis = System.currentMillis();
String currentTime = SimpleDateFormat("yyyy-MM-dd HH-mm-ss" ).format(currentTimeMillis);
本文完结!