java如何获取时间
获取当前时间
使用 java.util.Date 类可以获取当前时间:
Date currentDate = new Date();
System.out.println(currentDate);
使用 System.currentTimeMillis()
获取当前时间的毫秒数:
long currentTimeMillis = System.currentTimeMillis();
System.out.println(currentTimeMillis);
使用 java.time 包(Java 8及以上)
java.time 包提供了更现代的日期时间 API:

LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println(currentDateTime);
格式化日期时间
使用 SimpleDateFormat 或 DateTimeFormatter 格式化日期时间:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(new Date());
System.out.println(formattedDate);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = LocalDateTime.now().format(formatter);
System.out.println(formattedDateTime);
获取特定时间字段
使用 Calendar 类获取特定时间字段:

Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1; // 月份从0开始
int day = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(year + "-" + month + "-" + day);
使用 java.time 获取特定字段
LocalDate today = LocalDate.now();
int year = today.getYear();
int month = today.getMonthValue();
int day = today.getDayOfMonth();
System.out.println(year + "-" + month + "-" + day);
时区处理
使用 ZonedDateTime 处理带时区的日期时间:
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
System.out.println(zonedDateTime);
时间戳转换
将时间戳转换为 Date 或 LocalDateTime:
long timestamp = System.currentTimeMillis();
Date dateFromTimestamp = new Date(timestamp);
System.out.println(dateFromTimestamp);
LocalDateTime dateTimeFromTimestamp = Instant.ofEpochMilli(timestamp)
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
System.out.println(dateTimeFromTimestamp);






