Javaで時間を正しくフォーマットする方法は何ですか?
Javaで時間をフォーマットするために、SimpleDateFormatクラスを使用することができます。以下はサンプルコードです:
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeFormatting {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(date);
System.out.println("Formatted Date: " + formattedDate);
}
}
この例では、SimpleDateFormatオブジェクトを作成し、日付時刻の形式を”yyyy-MM-dd HH:mm:ss”に指定しました。次に、format()メソッドを使用してDateオブジェクトを指定した形式の文字列にフォーマットしました。最後に、フォーマットされた時間文字列を出力します。
このコードを実行すると、次の結果が出力されます:
Formatted Date: 2021-08-26 15:30:45