OffsetTime表示具有相對于UTC的固定區(qū)偏移的時(shí)間。
OffsetTime組合LocalTime和ZoneOffset。
系統(tǒng)默認(rèn)時(shí)區(qū)用于在使用now()的偏移時(shí)間時(shí)獲取區(qū)域偏移值。
以下代碼顯示如何創(chuàng)建偏移時(shí)間。
import java.time.OffsetTime; import java.time.ZoneOffset; public class Main { public static void main(String[] args) { // current offset time OffsetTime ot1 = OffsetTime.now(); System.out.println("Current offset time: " + ot1); // a zone offset +01:30 ZoneOffset offset = ZoneOffset.ofHoursMinutes(1, 30); OffsetTime offsetTime = OffsetTime.of(16, 40, 28, 0, offset); System.out.println(offsetTime); } }
上面的代碼生成以下結(jié)果。
OffsetDateTime表示datetime,固定區(qū)偏移UTC。
OffsetDateTime組合LocalDateTime和ZoneOffset。
我們可以從偏移日期和時(shí)間提取本地日期和時(shí)間。
系統(tǒng)默認(rèn)時(shí)區(qū)用于在偏移日期和時(shí)間使用now()時(shí)獲取區(qū)域偏移值。
以下代碼顯示如何創(chuàng)建偏移日期時(shí)間。
import java.time.LocalDate; import java.time.LocalTime; import java.time.OffsetDateTime; import java.time.ZoneOffset; public class Main { public static void main(String[] args) { // Get the current offset datetime OffsetDateTime OffsetDateTime odt1 = OffsetDateTime.now(); // Create an offset datetime OffsetDateTime odt2 = OffsetDateTime.of(2012, 5, 11, 18, 10, 30, 0, ZoneOffset.UTC); // Get the local date and time from the offset datetime LocalDate localDate = odt1.toLocalDate(); LocalTime localTime = odt1.toLocalTime(); System.out.println(localDate); System.out.println(localTime); } }
上面的代碼生成以下結(jié)果。
以下代碼顯示如何從即時(shí)創(chuàng)建偏移日期時(shí)間。
import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneId; public class Main { public static void main(String[] args) { Instant i1 = Instant.now(); ZoneId usChicago = ZoneId.of("America/Chicago"); OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant(i1, usChicago); System.out.println(offsetDateTime); } }
上面的代碼生成以下結(jié)果。
更多建議: