Java常用的时间转换和计算方式

Java常用的时间转换和计算方式

lixiangrong
2024-01-03 / 0 评论 / 19 阅读 / 正在检测是否收录...
// 获取当前时间的若干种方式
Date time1 = new Date();
Date time2 = Calendar.getInstance().getTime();
LocalDateTime time3 = LocalDateTime.now();
System.out.println(ZoneId.systemDefault());
ZonedDateTime time4 = Instant.now().atZone(ZoneId.systemDefault());
System.out.println(time1);
System.out.println(time2);
System.out.println(time3);
System.out.println(time4);

// 时间字符串转Date
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date1 = simpleDateFormat.parse("2023-03-17 08:30:00");
Date date2 = simpleDateFormat.parse("2023-03-17 12:31:00");

// Date转成时间字符串
String format = simpleDateFormat.format(date1);
System.out.println(format);

// 时间字符串转LocalDateTime
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parse1 = LocalDateTime.parse("2023-03-17 08:30:00", formatter);
LocalDateTime parse2 = LocalDateTime.parse("2023-03-17 12:31:00", formatter);

// LocalDateTime转成时间字符串
LocalDateTime localDateTimeNow = LocalDateTime.now();
String format1 = localDateTimeNow.format(formatter);
System.out.println(format1);

// 比较两个日期相差多少小时,date2 < date1则返回负数
System.out.println(Duration.between(date1.toInstant(), date2.toInstant()).toHours());
// 比较两个日期相差多少分钟,date2 < date1则返回负数
System.out.println(Duration.between(date1.toInstant(), date2.toInstant()).toMinutes());


// 比较两个日期相差多少小时,date2 < date1则返回负数
System.out.println(Duration.between(parse1,parse2).toHours());
System.out.println(ChronoUnit.HOURS.between(parse1, parse2));

System.out.println(date1.before(date2));
// Java常用比较两个时间差有四个类:Period、Duration、ChronoUnit、Until(通常用Period和Duration)
// Period类计算只有年、月、日,Duration类计算只有日、时、分、秒、毫秒
// ChronoUnit类计算有年、月、周、日、时、分、秒、毫秒,Until同ChronoUnit类一样
// 某时间距离当天结束还有多久
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parse1 = LocalDateTime.parse("2023-03-23 16:00:00", formatter);
LocalDateTime midnight = parse1.plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
long seconds = ChronoUnit.MINUTES.between(parse1,midnight);
System.out.println(formatter.format(parse1)+"距离当天结束剩余分钟数:" + seconds);



// 判断两个时间段是否有交集
// 判断用户正在报名的活动时间段与已经报名的活动时间段是否有交集
if (!oldStartTime.after(newStartTime) && !newEndTime.after(oldEndTime) || !oldStartTime.after(newStartTime) && !newStartTime.after(oldEndTime))
{
    return AjaxResult.error("你已经报名或正在参加活动!");
}
0

评论 (0)

取消