はじめに
getDayOfYear() メソッドは、指定された日付の年の日付を返します。このメソッドにはパラメータがなく、整数値を返します。getDayOfYear() メソッドを使用するには、LocalDate クラスのインスタンスを作成し、このインスタンスでメソッドを呼び出します。
必要なクラスをインポートする
LocalDate と DateTimeFormatter クラスを使用するために必要なクラスをインポートします。
import java.time.LocalDate;
getDayOfYear() メソッドを使用して年の日付を取得する
of() メソッドを使用して LocalDate インスタンスを作成し、日付を指定します。インスタンスで getDayOfYear() メソッドを呼び出して、年の日付を取得します。
public class LocalDateGetDayOfYearExample {
public static void main(String[] args){
// Create a LocalDate instance
LocalDate localDate = LocalDate.of(2021, 6, 10);
// Get the day of the year using getDayOfYear() method
int dayOfYear = localDate.getDayOfYear();
// Print the day of the year
System.out.println("Day Of Year: " + dayOfYear);
}
}
上記のコードでは、of() メソッドを使用して 2021 年 6 月 10 日の日付で LocalDate インスタンスを作成します。localDate インスタンスで getDayOfYear() メソッドを呼び出して、年の日付を取得します。最後に、println() メソッドを使用して年の日付を出力します。
次のコマンドを使用してコードをコンパイルして実行します。
javac LocalDateGetDayOfYearExample.java
java LocalDateGetDayOfYearExample
次の出力が表示されるはずです。
Day Of Year: 161
年の現在の日付を取得する
現在の年の日付を取得するには、now() メソッドを使用して LocalDate インスタンスを作成し、そのインスタンスで getDayOfYear() メソッドを呼び出します。
public class LocalDateGetDayOfYearExample {
public static void main(String[] args){
// Create a LocalDate instance
LocalDate localDate = LocalDate.now();
// Get the day of the year using getDayOfYear() method
int dayOfYear = localDate.getDayOfYear();
// Print the day of the year
System.out.println("Day Of Year: " + dayOfYear);
}
}
上記のコードでは、now() メソッドを使用して現在の日付で LocalDate インスタンスを作成します。localDate インスタンスで getDayOfYear() メソッドを呼び出して、年の日付を取得します。最後に、println() メソッドを使用して年の日付を出力します。
次のコマンドを使用してコードをコンパイルして実行します。
javac LocalDateGetDayOfYearExample.java
java LocalDateGetDayOfYearExample
年の現在の日付が出力として表示されるはずです。
DateTimeFormatter を使用して文字列形式で年の日付を取得する
DateTimeFormatter クラスを使用して、日付を好きな形式の文字列にフォーマットすることができます。
import java.time.format.DateTimeFormatter;
public class LocalDateGetDayOfYearExample {
public static void main(String[] args){
// Create a LocalDate instance
LocalDate localDate = LocalDate.now();
// Create an instance of DateTimeFormatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// Format the LocalDate into String
String formatDate = localDate.format(formatter);
// Get the day of the year using getDayOfYear() method
int dayOfYear = localDate.getDayOfYear();
// Print the day of the year
System.out.println("Day Of Year for " + formatDate + " is " + dayOfYear);
}
}
上記のコードでは、日付を "yyyy-MM-dd" 形式にフォーマットするために DateTimeFormatter インスタンスを作成します。その後、現在の日付をこの形式の文字列にフォーマットします。localDate インスタンスで getDayOfYear() メソッドを呼び出して、年の日付を取得します。最後に、println() メソッドを使用して年の日付とフォーマットされた日付文字列を出力します。
次のコマンドを使用してコードをコンパイルして実行します。
javac LocalDateGetDayOfYearExample.java
java LocalDateGetDayOfYearExample
年の現在の日付とフォーマットされた日付文字列が出力として表示されるはずです。
まとめ
この実験では、Java の LocalDate クラスの getDayOfYear() メソッドの使い方を学びました。また、年の現在の日付を取得し、好きな形式の文字列に日付をフォーマットする方法も学びました。



