java如何读取时间
读取当前时间
使用 java.time.LocalDateTime 可以获取当前日期和时间:
LocalDateTime now = LocalDateTime.now();
System.out.println("当前时间: " + now);
读取特定时间
通过 LocalDateTime.of() 方法可以创建指定时间:
LocalDateTime specificTime = LocalDateTime.of(2023, Month.JANUARY, 1, 12, 30, 45);
System.out.println("指定时间: " + specificTime);
格式化时间输出
使用 DateTimeFormatter 可以自定义时间格式:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedTime = now.format(formatter);
System.out.println("格式化时间: " + formattedTime);
读取时间各部分
通过 LocalDateTime 可以分别获取年、月、日、时、分、秒:
int year = now.getYear();
int month = now.getMonthValue();
int day = now.getDayOfMonth();
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();
System.out.printf("%d年%d月%d日 %d:%d:%d%n", year, month, day, hour, minute, second);
使用旧版 Date 类
如果需要使用旧版 API,可以通过 java.util.Date:
Date date = new Date();
System.out.println("旧版时间: " + date);
时间戳转换
从时间戳获取时间:

long timestamp = System.currentTimeMillis();
Instant instant = Instant.ofEpochMilli(timestamp);
LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
System.out.println("时间戳转换: " + dateTime);






