java如何设置时间
设置当前时间
在Java中获取当前时间通常使用java.util.Date或java.time包(Java 8及以上版本)。以下是两种常用方式:
// 使用java.util.Date
Date currentDate = new Date();
// 使用java.time.LocalDateTime
LocalDateTime currentDateTime = LocalDateTime.now();
设置特定时间
使用java.time包可以精确设置年月日时分秒:

// 设置固定日期时间
LocalDateTime specificDateTime = LocalDateTime.of(2023, 10, 15, 14, 30, 45);
// 设置日期(不含时间)
LocalDate date = LocalDate.of(2023, 10, 15);
// 设置时间(不含日期)
LocalTime time = LocalTime.of(14, 30, 45);
时间格式化输出
使用DateTimeFormatter将时间转换为指定格式字符串:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = LocalDateTime.now().format(formatter);
时间戳转换
时间戳(毫秒数)与日期对象互相转换:

// 时间戳转日期
Instant instant = Instant.ofEpochMilli(1609459200000L);
LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
// 日期转时间戳
long timestamp = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli();
时区处理
处理不同时区的时间:
// 获取指定时区时间
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("America/New_York"));
// 时区转换
ZonedDateTime tokyoTime = zonedDateTime.withZoneSameInstant(ZoneId.of("Asia/Tokyo"));
日历操作(Calendar类)
传统Calendar类的使用方法:
Calendar calendar = Calendar.getInstance();
calendar.set(2023, Calendar.OCTOBER, 15, 14, 30, 45);
Date date = calendar.getTime();
注意:Java 8及以上推荐使用java.time包,它提供了更直观和线程安全的API。






