JSR 310日期时间体系:
- LocalDateTime:本地日期时间
- OffsetDateTime:带偏移量的日期时间
- ZonedDateTime:带时区的日期时间
目录
- 构造
- 计算
- 格式化
- 参考文章
日期时间包
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
构造
LocalDateTime
// 获取本地时间
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
// 2023-09-20T15:12:35.899// 获取当前的纽约时间
LocalDateTime nowNewYork = LocalDateTime.now(ZoneId.of("America/New_York"));
System.out.println(nowNewYork);
// 2023-09-20T03:12:35.902
OffsetDateTime
OffsetDateTime now = OffsetDateTime.now();
System.out.println(now);
// 2023-09-20T15:36:41.490+08:00
ZonedDateTime
ZonedDateTime now = ZonedDateTime.now();
System.out.println(now);
// 2023-09-20T15:36:02.513+08:00[Asia/Shanghai]
计算
// 获取本地时间
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
// 2023-09-20T15:21:06.789// + 3天
LocalDateTime now3 = now.plusDays(3);
System.out.println(now3);
// 2023-09-23T15:21:06.789// -4天
LocalDateTime now4 = now.minusDays(4);
System.out.println(now4);
// 2023-09-16T15:21:06.789// 计算天数
Period between = Period.between(now.toLocalDate(), now3.toLocalDate());
System.out.println(between.getDays());
// 3// 计算小时数
Duration between1 = Duration.between(now.toLocalTime(), now3.toLocalTime());
System.out.println(between1.toHours());
// 0
格式化
// 获取本地时间
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
// 2023-09-20T15:25:46.454// 格式化
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String format = dateTimeFormatter.format(now);
System.out.println(format);
// 2023-09-20 15:25:46// 解析时间格式的字符串
LocalDateTime parse = LocalDateTime.parse(format, dateTimeFormatter);
System.out.println(parse);
// 2023-09-20T15:27:15
参考文章
- LocalDateTime、OffsetDateTime、ZonedDateTime互转,这一篇绝对喂饱你