新的日期時間API
1 日期/時間
LocalDate:沒有時區的日期
LocalTime:沒有時區的時間
LocalDateTime:沒有時區的日期時間
ZonedDateTime:有時區的日期時間
時區/ZoneId
ZoneId.getAvailableZoneIds()獲取所有可用的ZoneId,
偏移量/ZoneOffset
偏移量指的是偏移UTC時區的時分秒,
如:+08:00的意思時超前于UTC八個小時,而 -05:45 意思是落后于UTC五小時四十五分鐘,
因為有著夏/冬令時的區分,所以偏移量會發生變化,
獲取日期時間資訊
LocalDateTime localDateTime = LocalDateTime.now();
//很多,不一一寫出來
localDateTime.getXXX();
日期時間調整
- 加減
LocalDateTime localDateTime = LocalDateTime.now();
//很多,不一一寫出來
localDateTime.minusXXX();
- 修改
LocalDateTime localDateTime = LocalDateTime.now();
//很多,不一一寫出來
localDateTime.withXXX();
日期時間比較
LocalDateTime time1 = LocalDateTime.now();
LocalDateTime time2 = time1.minusDays(1);
int compare = time1.compareTo(time2);
boolean after = time1.isAfter(time2);
boolean before = time1.isBefore(time2);
boolean equal = time1.isEqual(time2);
格式化
LocalDateTime time = LocalDateTime.now();
time.format(DateTimeFormatter.ofPattern("yyyyMM"));
TemporalAdjuster
LocalDateTime time = LocalDateTime.now();
time.with(TemporalAdjusters.xxx());
//dayOfWeekInMonth() – 一周中的某一天,例如,三月中第二個星期二
//firstDayOfMonth() – 當前月的第一天
//firstDayOfNextMonth() – 下一個月的第一天
//firstDayOfNextYear() – 下一年的第一天
//firstDayOfYear() – 當年的第一天
//lastDayOfMonth() – 當月的最后一天
//nextOrSame() – 下一次或當天發生的一周中的某天
2 時間戳與時間段
Instant
時間戳,
表示Unix元年(傳統的設定為UTC時區1970年1月1日午夜時分)開始所經歷的時間,
Instant instant = Instant.now();
long epochSecond = instant.getEpochSecond();//秒數
long l = instant.toEpochMilli();//毫秒數
System.out.println(epochSecond);
System.out.println(l);
Period
基于日期的時間段,
LocalDate start = LocalDate.of(2020, 7, 28);
LocalDate end = LocalDate.of(2020, 7, 29);
Period period = Period.between(start, end);
boolean negative = period.isNegative();//判斷start end的大小
System.out.println(period);//格式為P-1Y-1M-30D
//基于年與日的時間段
Duration
基于時間的時間段,
Instant start = Instant.parse("2020-07-09T06:07:30.00Z");
Instant end = Instant.parse("2019-05-07T11:12:37.20Z");
Duration duration = Duration.between(start, end);
boolean negative = duration.isNegative();//判斷start end的大小
System.out.println(duration);//格式為PT-10290H-54M-52.8S
//基于時分秒的時間段
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/125383.html
標籤:Java
上一篇:JVM類加載機制
下一篇:一分鐘玩轉 Spring IoC
