Java8 新特性 - 新时间与日期API
package com.xq.java8; import org.junit.jupiter.api.Test; import java.time.*; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAdjusters; import java.util.Set; public class TestLocalDateTime { // ZonedDate、ZonedTime、ZonedDateTime @Test public void test7(){ Set<String> set = ZoneId.getAvailableZoneIds(); set.forEach(System.out::println); } @Test public void test8(){ LocalDateTime ldt = LocalDateTime.now(ZoneId.of("America/Rosario")); System.out.println(ldt); LocalDateTime ldt2 = LocalDateTime.now(ZoneId.of("America/Rosario")); ZonedDateTime zdt = ldt2.atZone(ZoneId.of("America/Rosario")); System.out.println(zdt); } //DateTimeFormatter : 格式化时间 / 日期 @Test public void test6(){ DateTimeFormatter dt = DateTimeFormatter.ISO_DATE; LocalDateTime ldt = LocalDateTime.now(); String str = ldt.format(dt); System.out.println(str); System.out.println("--------------------"); DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss"); String strDate2 = dtf2.format(ldt); System.out.println(strDate2); LocalDateTime newdate = ldt.parse(strDate2,dtf2); System.out.println(newdate); } // TemporalAdjuster:时间校正器 @Test public void test5(){ LocalDateTime ldt = LocalDateTime.now(); System.out.println(ldt); LocalDateTime ldt2 = ldt.withDayOfMonth(10); System.out.println(ldt2); LocalDateTime ldt3 = ldt.with(TemporalAdjusters.next(DayOfWeek.SUNDAY)); System.out.println(ldt3); // 自定义:下一个工作日 LocalDateTime ldt5 = ldt.with((l) -> { LocalDateTime ldt4 = (LocalDateTime)l; DayOfWeek dow = ldt4.getDayOfWeek(); if(dow.equals(DayOfWeek.FRIDAY)){ return ldt4.plusDays(3); } else if(dow.equals(DayOfWeek.SATURDAY)){ return ldt4.plusDays(2); } else { return ldt4.plusDays(1); } }); System.out.println(ldt5); } // 1.LocalDate LocalTime LocalDateTime // 2. Instant: 时间戳(以 Unix 元年:1970年1月1日 00:00:00 到某个时间的毫秒值) @Test public void test2(){ Instant ins1 = Instant.now(); System.out.println(ins1); OffsetDateTime odt = ins1.atOffset(ZoneOffset.ofHours(8)); System.out.println(odt); System.out.println(ins1.toEpochMilli()); } @Test public void test1(){ LocalDateTime ldt = LocalDateTime.now(); System.out.println(ldt); LocalDateTime ldt2 = LocalDateTime.of(2020,5,13,13,11,33); System.out.println(ldt2); LocalDateTime ldt3 = ldt.plusYears(2); System.out.println(ldt3); LocalDateTime ldt4 = ldt.minusMonths(2); System.out.println(ldt4); 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()); } }
本文来自博客园,作者:l-coil,转载请注明原文链接:https://www.cnblogs.com/l-coil/p/12905984.html