本地时间与时间戳
LocalDate 、 LocalTime 、 LocalDateTime 类的实例是不可变的对象,分别表示使用iso-8601历系统的日期、时间、日期和时间。它提供了简单的日期或时间,并不包含当前的时间信息。也不包含与时区相关的信息。
本地时间
// LocalDate LocalTime LocalDateTime@Testpublic void test01(){// 获取当前日期和时间LocalDateTime ldt = LocalDateTime.now();System.out.println(ldt);// 自定义日期时间返回一个LocalDateTime实例LocalDateTime of = LocalDateTime.of(2015, 10, 19, 13, 22, 33);System.out.println(of);// 年份增加,返回一个新的实例LocalDateTime localDateTime = ldt.plusYears(10);System.out.println(localDateTime);// 年份减少,返回一个新的实例LocalDateTime localDateTime1 = ldt.minusYears(10);System.out.println(localDateTime1);// 获取年、月、日、时、分、秒System.out.println(ldt.getYear());System.out.println(ldt.getMonthValue());System.out.println(ldt.getDayOfMonth());System.out.println(ldt.getHour());System.out.println(ldt.getMinute());System.out.println(ldt.getSecond());}
时间戳
以Unix元年:1970年1月1日00:00:00到某个时间之间的毫秒值被称为时间戳。
Instant
@Testpublic void test02(){// 默认获取 UTC 时区的时间 UTC(世界协调时间)Instant now = Instant.now();System.out.println(now);// 设置偏移量的时间OffsetDateTime offsetDateTime = now.atOffset(ZoneOffset.ofHours(8));System.out.println(offsetDateTime);// 毫秒显示long l = now.toEpochMilli();System.out.println(l);// 设置从1970年1月1日00:00:00 在加上1秒开始计算Instant instant = Instant.ofEpochSecond(1);System.out.println(instant);}
Duration:两个时间之间的间隔
@Testpublic void test03() throws InterruptedException {// Duration:计算两个时间之间的间隔Instant now1 = Instant.now();Thread.sleep(1000);Instant now2 = Instant.now();Duration between = Duration.between(now1, now2);System.out.println(between.toMillis());}
@Testpublic void test04() throws InterruptedException {LocalTime l1 = LocalTime.now();Thread.sleep(1000);LocalTime l2 = LocalTime.now();Duration between = Duration.between(l1, l2);System.out.println(between.toMillis());}
Period:计算两个日期之间的间隔
@Testpublic void test05(){LocalDate ld = LocalDate.of(2015,10,10);LocalDate ld2 = LocalDate.of(2020,12,20);Period between = Period.between(ld, ld2);System.out.println(between.getYears());// 相差年System.out.println(between.getMonths());// 相差月System.out.println(between.getDays());// 相差日}
时间矫正器
