TL;博士
ZonedDateTime.of(
LocalDate.now(ZoneId.of("Pacific/Auckland")) // Determine today’s date for a given region.
.plusDays(1) , // Determine day-after, tomorrow.
LocalTime.parse( // Parse string with AM/PM into `LocalTime` object.
"6:51:35 PM" ,
DateTimeFormatter.ofPattern("h:m:s a").withLocale(Locale.US)
) , // Combine date with time-of-day…
ZoneId.of("Pacific/Auckland") // …and zone…
) // …to produce a `ZonedDateTime`, a point on the timeline.
.toString() // Generate a String in standard ISO 8601 format, wisely extended by appending the name of the time zone in square brackets.
2018-02-02T18:51:35 + 13:00 [太平洋/奧克蘭]
java.time
解析傳入以12小時的格式將字符串轉換爲LocalTime
對象。
String input = "6:51:35 PM" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern("h:m:s a").withLocale(Locale.US) ;
LocalTime lt = LocalTime.parse(input , f) ;
要設置鬧鐘,您需要結合日期以及時區來確定實際時刻。
LocalDate
類代表沒有時間和沒有時區的僅有日期的值。
時區對確定日期至關重要。對於任何特定的時刻,日期因地區而異。例如,Paris France午夜後幾分鐘是新的一天,而在Montréal Québec仍然是「昨天」。
如果未指定時區,則JVM將隱式應用其當前默認時區。該默認值可能隨時改變,因此您的結果可能會有所不同。最好明確指定所需的/預期的時區作爲參數。
在continent/region
的格式指定一個proper time zone name,如America/Montreal
,Africa/Casablanca
,或Pacific/Auckland
。切勿使用3-4字母縮寫,如EST
或IST
,因爲它們是而不是真正的時區,不是標準化的,甚至不是唯一的(!)。
ZoneId z = ZoneId.of("America/Montreal") ;
LocalDate today = LocalDate.now(z) ;
如果要使用JVM的當前默認時區,請求它並作爲參數傳遞。如果省略,則隱式應用JVM的當前默認值。最好是明確的。
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
通過增加一天來確定明天。
LocalDate tomorrow = today.plusDays(1) ;
應用所需的時區的時間 - 日期和以產生ZonedDateTime
。如果由於諸如夏令時(DST)之類的異常,您的時間在該地區的該日期無效,該課程將自動進行調整。閱讀文檔以確保您理解並同意這些調整的行爲。
ZonedDateTime zdt = ZonedDateTime.of(tomorrow , lt , z) ; // Get a specific moment in time given a particular date, time-of-day, and zone.
關於java.time
的java.time框架是建立在Java 8和更高版本。這些類代替了日期時間類legacy,如java.util.Date
,Calendar
,& SimpleDateFormat
。
Joda-Time項目,現在在maintenance mode,建議遷移到java.time類。請參閱Oracle Tutorial。並搜索堆棧溢出了很多例子和解釋。規格是JSR 310。
從何處獲取java.time類?
謝謝你怎麼又定義上午或下午 – Somk
calendar.set(Calendar.AM_PM,HourValue <12 Calendar.AM:Calendar.PM)應該這樣做 – ErikR