Java LocalDateTimeを文字列に変換する方法【基本とサンプルコード】
Javaでは、LocalDateTimeオブジェクトを文字列に変換するためにDateTimeFormatterクラスを使用することができます。以下はサンプルコードです:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = now.format(formatter);
System.out.println("Formatted LocalDateTime: " + formattedDateTime);
}
}
上記のコードでは、まずLocalDateTimeオブジェクトを作成して現在の日付と時刻を表しました。次にDateTimeFormatterクラスを使用してフォーマットテンプレートを作成し、最後にLocalDateTimeオブジェクトのformatメソッドを呼び出して文字列に変換し、出力しました。