talosのプログラミング教室

Java Gold合格への道 ~日付/時刻API・from~

スポンサーリンク

こんにちは。たろすです。

今回は日付/時刻APIのfromについて説明します。

使い方

fromメソッドは日時を表すオブジェクトから別の日時を表すオブジェクトを取得する際に利用します。

LocalDateTime now = LocalDateTime.now();
System.out.println(LocalDate.from(now));
2022-05-03

注意点

情報が多い日時オブジェクトから情報が小さい日時オブジェクトの取得(例:LocalDateTimeからLocalDate)はできますが、逆はできません。

例外がスローされます。

LocalDateTime now = LocalDateTime.now();
System.out.println(ZonedDateTime.from(now));
Exception in thread "main" java.time.DateTimeException: Unable to obtain ZonedDateTime from TemporalAccessor: 2022-01-19T18:09:46.073 of type java.time.LocalDateTime
	at java.time.ZonedDateTime.from(ZonedDateTime.java:565)
	at from.Main.main(Main.java:15)
Caused by: java.time.DateTimeException: Unable to obtain ZoneId from TemporalAccessor: 2022-01-19T18:09:46.073 of type java.time.LocalDateTime
	at java.time.ZoneId.from(ZoneId.java:466)
	at java.time.ZonedDateTime.from(ZonedDateTime.java:553)
	... 1 more

おわりに

今回は日付/時刻APIのfromについて説明しました。