1、特征
LocalDateTime类的关键特征:
1、LocalDateTime是java.time包中的一个不可变类(immutable class)。
2、内部实现使用了LocalDate和LocalTime。
3、不包含时区信息,是一个本地日期和时间的组合。
最主要的特性如下:1、不可变性(Immutability): LocalDateTime是不可变的,这意味着一旦创建了对象,就无法更改其内容。任何对日期和时间的修改都会返回一个新的LocalDateTime对象。
2、线程安全性: 由于不可变性,LocalDateTime是线程安全的。多个线程可以同时访问对象而无需担心并发问题。
3、工厂方法: 除了使用of方法创建LocalDateTime对象外,还有一些静态工厂方法,如now、ofInstant、ofEpochSecond等,用于根据不同的情况创建实例。
4、日期时间调整: LocalDateTime提供了plus、minus等方法,用于执行日期和时间的调整操作。这些方法返回新的对象,而不是修改原始对象。
5、格式化和解析: LocalDateTime支持DateTimeFormatter用于格式化和解析日期时间。你可以创建自定义的格式化模式。
2.、常用方法
获取当前日期时间:
LocalDateTime currentDateTime = LocalDateTime.now();
创建指定日期时间:
LocalDateTime specificDateTime = LocalDateTime.of(2022, Month.JANUARY, 1, 12, 30);
获取日期和时间部分:
LocalDate datePart = specificDateTime.toLocalDate();
LocalTime timePart = specificDateTime.toLocalTime();
日期时间加减操作:
LocalDateTime newDateTime = specificDateTime.plusDays(1).minusHours(3);
比较:
boolean isAfter = specificDateTime.isAfter(currentDateTime);
格式化和解析(将字符串转换为formattedDateTime ):
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = specificDateTime.format(formatter);LocalDateTime parsedDateTime = LocalDateTime.parse("2022-01-01 12:30:00", formatter);
// 设置自动确定考勤时间为今天晚上的23点59分59秒 LocalDateTime now = LocalDateTime.now().with(LocalTime.MAX); // 转换成字符串 String formattedDateTime = now.format(formatter);
时间比较:比较时间差,计算分钟进行转换,直接获取小时会丢失分钟
// 备注时间(小时) nteger h = Integer.valueOf(startTimeData.substring(0,2)); // 备注时间(分钟) Integer m = Integer.valueOf(startTimeData.substring(3)); // 开始时间(早上9点) LocalTime startTime = LocalTime.of(h, m); // 开始时间 // 结束时间 LocalTime LetStartTime = LocalTime.of(17,30); // 结束时间:下午17点30 // 计算相差时间 // Duration duration = Duration.between(startTime, LetStartTime); // long hour = duration.toHours(); // 获取小时数 long minutes = ChronoUnit.MINUTES.between(startTime, LetStartTime); // 计算分钟数差 double hour = (double) minutes / 60; // 将分钟数转换为小时数,包括小数部分