一.LocalDate,LocalTime,LocalDateTime
LocalDate,LocalTime,LocalDateTime类的实例是不可改变的,分别表示使用ISO-8601日历系统的日期,时间,日期和时间。他们提供了简单的日期或时间,并不包含当前的时间信息。也不包含与地区相关的信息。
//1.当前时间对象
LocalDateTime ldt = LocalDateTime.now();
System.out.println(ldt);
//2.自定义时间对象
LocalDateTime ldt2 = LocalDateTime.of(2020,4,13,8,8,50);
System.out.println(ldt2);
//3.加时间
LocalDateTime localDateTime = ldt.plusDays(2);
//4.减时间
ldt.minusDays(1);
//5.获取时间
System.out.println(localDateTime.getDayOfMonth());
二.Instant 时间戳 (以Unix元年1970.1.1 0:0:0)到某个时间之间的毫秒值
//1.获取默认UTC时区
Instant now = Instant.now();
//2.获取8个时区的时间
OffsetDateTime odt = now.atOffset(ZoneOffset.ofHours(8));
//3.取得时间戳
long l = now.toEpochMilli();
//4.向Unix元年之后1秒
Instant instant = Instant.ofEpochSecond(1);
三.Duration Period
/**
* Duration : 计算两个‘时间‘ 之间的间隔
* Period : 计算两个‘日期‘ 之间的间隔
*/
Instant now1 = Instant.now();
Instant onehour = now.plusSeconds(60 * 60);
Duration between = Duration.between(now1, onehour);
System.out.println(between.toSeconds());
LocalDate ld01 = LocalDate.now();
LocalDate ld02 = LocalDate.of(2020, 4, 15);
Period between1 = Period.between(ld01, ld02);
System.out.println(between1.getDays());
四.TemporalAdjuster 时间校正器
TemporalAdjuster:时间矫正器。有时我们可能需要获取例如:将日期调整到"下个周日"等操作。
TemporalAdjusters:该类通过静态方法提供了大量的常用TemporalAdjuster的实现。
LocalDateTime now = LocalDateTime.now();
//获取这个月的第一天
LocalDateTime with = now.with(TemporalAdjusters.firstDayOfMonth());
//获取这个月第一个星期二
LocalDateTime with1 = now.with(TemporalAdjusters.dayOfWeekInMonth(1, DayOfWeek.TUESDAY));
//自定义:下一个工作日
LocalDateTime nextWorkDay = now.with((x) -> {
//传递来的参数
LocalDateTime ldt = (LocalDateTime) x;
//如果传来的周五,那么下个工作日就是三天后
if (ldt.equals(DayOfWeek.FRIDAY)) {
return ldt.plusDays(3);
} else if (ldt.equals(DayOfWeek.SATURDAY)) {
return ldt.plusDays(2);
} else {
return ldt.plusDays(1);
}
});
五.DateTimeFormatter :格式化日期/时间
//定义格式化格式
DateTimeFormatter dft = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
LocalDateTime now = LocalDateTime.now();
String format = now.format(dft);
//自定义格式化格式
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String format1 = now.format(dateTimeFormatter);
//字符串格式转换为日期 如果只用年月日就只能转换为LocalDate
LocalDate ld = LocalDate.parse(format1,dateTimeFormatter);
System.out.println(ld.getDayOfMonth());
六.ZonedDate,ZonedTime,ZonedDateTime
其中每个时区都对应着ID,地区ID都为 " {区域}/{城市} "的格式
ZoneId :该类中包含了所有的时区信息
getAvailableZoneIds() :可以获取所有时区的时区信息
of(id) :用指定的时区信息获取ZoneId对象
//1.查看支持的所有时区信息
Set<String> set = ZoneId.getAvailableZoneIds();
set.forEach(System.out::println);
//2.取得指定时区的时间 2020-04-14T00:54:04.797825100
LocalDateTime now = LocalDateTime.now(ZoneId.of("Asia/Tokyo"));
System.out.println(now);
//3.带时区信息的时间 2020-04-13T23:54:04.800817600+09:00[Asia/Tokyo]
LocalDateTime now1 = LocalDateTime.now(ZoneId.of("Asia/Tokyo"));
ZonedDateTime zonedDateTime = now1.atZone(ZoneId.of("Asia/Tokyo"));
System.out.println(zonedDateTime);
原文:https://www.cnblogs.com/licha233/p/12695141.html