1. 程式人生 > 其它 >java.time包閱讀筆記

java.time包閱讀筆記

預備知識

java.time包概述

  • 所有的class都是immutable和thread-safe

各個包之間的關係

  • java.time.temporal提供對時間的低層級訪問
  • java.time.format提供格式
  • java.time.chrono包含日曆無關(calendar neutral)的API

Dates and Times

Instant

  • a numeric timestamp

LocalDate

LocalTime

LocalDateTime

ZonedDateTime

  • 一般不需要使用

  • "Where possible, it is recommended to use a simpler class without a time-zone. The widespread use of time-zones tends to add considerable complexity to an application."

Duration and Period

Duration

  • 以納秒錶示的時間差

Period

  • 以對人類有意義的時間單位(年月日)表示的時間差

Additional value types

Month

  • 例如,’DECEMBER‘

DayOfWeek

  • 例如,’THUESDAY‘

Year

  • 例如,’2021‘

YearMonth

  • 例如,’2021-07‘

MonthYear

  • 例如,‘--07-01’

OffsetTime

  • 例如,‘15:07:46.964842600+08:00’
  • 表示15:07分,目前處於東八區

Design Note

  • Instant是Java.util.Date的最接近的等價類

  • ZonedDateTime是java.util.GregorianCalendar的最接近的等價類

  • OffsetTime和OffsetDateTime主要用於網路協議和資料庫訪問,因為大多數資料庫無法將諸如‘Europe/Paris’這樣的時區資訊進行自動轉換並存儲,但是對於偏移卻可以

  • 統一的方法介面

    • of - static factory method
      parse - static factory method focussed on parsing
      get - gets the value of something
      is - checks if something is true
      with - the immutable equivalent of a setter
      plus - adds an amount to an object
      minus - subtracts an amount from an object
      to - converts this object to another type
      at - combines this object with another, such as date.atTime(time)
      
  • 資料以ISO Calendar標準儲存

  • 不同日期之間的轉換需要使用到java.time.chrono包