ChronoField枚舉定義了一組標準字段,如 AMPM_OF_DAY,DAY_OF_MONTH,DAY_OF_WEEK,DAY_OF_YEAR,ERA,
HOUR_OF_DAY,MINUTE_OF_HOUR,MONTH_OF_YEAR,年年約SECOND_OF_MINUTE,YEAR_OF_ERA 。
以下代碼顯示了如何使用 ChronoField
從datetime中提取字段值。
import java.time.LocalDateTime; import java.time.temporal.ChronoField; public class Main { public static void main(String[] args) { LocalDateTime now = LocalDateTime.now(); System.out.println(now.get(ChronoField.YEAR)); System.out.println(now.get(ChronoField.MONTH_OF_YEAR)); System.out.println(now.get(ChronoField.DAY_OF_MONTH)); System.out.println(now.get(ChronoField.HOUR_OF_DAY)); System.out.println(now.get(ChronoField.HOUR_OF_AMPM)); System.out.println(now.get(ChronoField.AMPM_OF_DAY)); } }
上面的代碼生成以下結果。
以下代碼顯示了如何檢查數(shù)據(jù)時間對象是否支持ChronoField。
import java.time.LocalDateTime; import java.time.temporal.ChronoField; public class Main { public static void main(String[] args) { LocalDateTime now = LocalDateTime.now(); System.out.println(now.isSupported(ChronoField.YEAR)); System.out.println(now.isSupported(ChronoField.HOUR_OF_DAY)); System.out.println(ChronoField.YEAR.isSupportedBy(now)); System.out.println(ChronoField.HOUR_OF_DAY.isSupportedBy(now)); } }
上面的代碼生成以下結果。
ChronoUnit枚舉表示時間單位。
它包含以下常量:CENTURIES,DAYS,DECADES,ERAS,F(xiàn)OREVER,HALF_DAYS,HOURS,MICROS,MILLENNIA,MILLIS,MINUTES,MONTHS,NANOS,SECONDS,WEEKS和YEARS。
以下代碼顯示了如何使用ChronoUnit枚舉常量。
import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; public class Main { public static void main(String[] args) { LocalDateTime now = LocalDateTime.now(); // Get the date time 10 days ago LocalDateTime localDateTime1 = now.minus(10, ChronoUnit.DAYS); System.out.println(localDateTime1); } }
上面的代碼生成以下結果。
更多建議: