java如何获取时间
获取当前时间的方法
在Java中获取当前时间有多种方式,以下是几种常见的方法:
使用java.util.Date类
Date currentDate = new Date();
System.out.println(currentDate);
使用java.time.LocalDateTime(Java 8及以上版本推荐)
LocalDateTime currentTime = LocalDateTime.now();
System.out.println(currentTime);
使用java.time.LocalDate(仅获取日期部分)
LocalDate currentDate = LocalDate.now();
System.out.println(currentDate);
使用java.time.LocalTime(仅获取时间部分)

LocalTime currentTime = LocalTime.now();
System.out.println(currentTime);
使用System.currentTimeMillis()(获取毫秒时间戳)
long timestamp = System.currentTimeMillis();
System.out.println(timestamp);
格式化时间输出
可以使用DateTimeFormatter来格式化时间输出:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedTime = LocalDateTime.now().format(formatter);
System.out.println(formattedTime);
时区相关时间获取
获取特定时区的时间

ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
System.out.println(zonedDateTime);
使用java.util.Calendar(旧版API)
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime());
时间戳与日期对象转换
时间戳转Date对象
long timestamp = System.currentTimeMillis();
Date date = new Date(timestamp);
Date对象转时间戳
Date date = new Date();
long timestamp = date.getTime();
对于新项目,推荐使用Java 8引入的java.time包中的类,它们提供了更直观、线程安全的API。旧版Date和Calendar类存在设计缺陷,应尽量避免在新代码中使用。






