java中如何获取当前时间
获取当前时间的几种方法
使用 java.time 包(Java 8及以上推荐)
import java.time.LocalDateTime;
LocalDateTime currentTime = LocalDateTime.now();
System.out.println("当前时间: " + currentTime);
使用 System.currentTimeMillis()
long currentTimeMillis = System.currentTimeMillis();
System.out.println("当前时间戳(毫秒): " + currentTimeMillis);
使用 java.util.Date
import java.util.Date;
Date currentDate = new Date();
System.out.println("当前时间: " + currentDate);
使用 java.util.Calendar
import java.util.Calendar;
Calendar calendar = Calendar.getInstance();
System.out.println("当前时间: " + calendar.getTime());
格式化输出时间
import java.time.format.DateTimeFormatter;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedTime = LocalDateTime.now().format(formatter);
System.out.println("格式化时间: " + formattedTime);
获取特定时区的时间
import java.time.ZoneId;
import java.time.ZonedDateTime;
ZonedDateTime zonedTime = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
System.out.println("上海时区时间: " + zonedTime);
获取当前时间的各个部分
LocalDateTime now = LocalDateTime.now();
int year = now.getYear();
int month = now.getMonthValue();
int day = now.getDayOfMonth();
int hour = now.getHour();
int minute = now.getMinute();
System.out.printf("%d年%d月%d日 %d时%d分%n", year, month, day, hour, minute);
注意事项
java.time 包是Java 8引入的现代日期时间API,推荐使用
Date 和 Calendar 是旧API,存在线程安全等问题
- 时间格式化可以使用
DateTimeFormatter 类
- 处理时区时建议明确指定,避免依赖系统默认时区

