java怎么获取当前时间并转换格式
在Java中,可以使用java.util.Date
类或java.time.LocalDateTime
类来获取当前时间并转换格式。
使用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.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);