Get Current Time in Java: Format Conversion Guide

In Java, you can use either the java.util.Date class or the java.time.LocalDateTime class to obtain the current time and format it.

Utilize the java.util.Date class:

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);

Utilize the java.time.LocalDateTime class:

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