Java 現在時刻の取得とフォーマット変更【SimpleDateFormat】

Javaでは、現在の時間を取得してフォーマット変換するためには、java.util.Dateクラスまたはjava.time.LocalDateTimeクラスを使用できます。

Javaのjava.util.Dateクラスを使用します。

import java.util.Date;
import java.text.SimpleDateFormat;

// 获取当前时间
Date currentDate = new Date();

// 创建日期格式化对象
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// 格式化日期
String formattedDate = format.format(currentDate);

System.out.println("当前时间:" + formattedDate);

Javaのjava.time.LocalDateTimeクラスを使用する。

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

// 获取当前时间
LocalDateTime currentDateTime = LocalDateTime.now();

// 创建日期时间格式化对象
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

// 格式化日期时间
String formattedDateTime = currentDateTime.format(formatter);

System.out.println("当前时间:" + formattedDateTime);
bannerAds