Java获取当前年月日时分秒毫秒的方法有多种。下面我将介绍两种常用的方式。
方式一:使用Java提供的Date类和SimpleDateFormat类
`java
import java.util.Date;
import java.text.SimpleDateFormat;
public class GetCurrentDateTime {
public static void main(String[] args) {
// 获取当前时间
Date date = new Date();
// 设置日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
// 格式化日期
String currentDateTime = sdf.format(date);
// 输出结果
System.out.println("当前时间:" + currentDateTime);
}
上述代码中,我们首先使用Date类获取当前时间,然后使用SimpleDateFormat类来设置日期格式,并将当前时间格式化为指定格式的字符串。我们将格式化后的字符串输出。
方式二:使用Java 8引入的新日期时间API
`java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class GetCurrentDateTime {
public static void main(String[] args) {
// 获取当前时间
LocalDateTime now = LocalDateTime.now();
// 设置日期格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
// 格式化日期
String currentDateTime = now.format(formatter);
// 输出结果
System.out.println("当前时间:" + currentDateTime);
}
在Java 8中,引入了新的日期时间API,其中LocalDateTime类代表了日期和时间。我们可以使用LocalDateTime.now()方法获取当前时间,然后使用DateTimeFormatter类设置日期格式,并将当前时间格式化为指定格式的字符串。我们将格式化后的字符串输出。
这两种方式都可以获取当前年月日时分秒毫秒,你可以根据自己的需要选择使用哪种方式。