温馨提示×

java怎么获取当前时间并转换格式

小亿
88
2024-02-29 10:18:15
栏目: 编程语言

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

0