java如何转换时间
时间转换方法
使用 SimpleDateFormat 类
通过 SimpleDateFormat 可以实现字符串与 Date 对象的相互转换。设置目标格式时需指定模式(如 yyyy-MM-dd HH:mm:ss)。注意线程安全问题,建议每次创建新实例或使用线程局部变量。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sdf.format(new Date()); // Date转字符串
Date date = sdf.parse("2023-10-01 12:00:00"); // 字符串转Date
Java 8+ 的 DateTimeFormatterDateTimeFormatter 是线程安全的替代方案,配合 LocalDateTime、ZonedDateTime 等新API使用。支持更灵活的时间操作和时区处理。
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDateTime = LocalDateTime.parse("2023-10-01 12:00:00", formatter);
String formattedDate = localDateTime.format(formatter);
时区转换
使用 ZonedDateTime 可明确处理时区问题。例如将UTC时间转换为系统默认时区:
ZonedDateTime utcTime = ZonedDateTime.now(ZoneOffset.UTC);
ZonedDateTime localTime = utcTime.withZoneSameInstant(ZoneId.systemDefault());
时间戳与对象转换
时间戳(毫秒数)与 Date 或 Instant 的转换:
long timestamp = System.currentTimeMillis();
Date dateFromTimestamp = new Date(timestamp);
Instant instant = Instant.ofEpochMilli(timestamp);
注意事项

- 旧版
Date和Calendar存在设计缺陷,推荐优先使用Java 8+的时间API。 - 格式模式区分大小写(如
MM表示月份,mm表示分钟)。 - 异常处理需捕获
ParseException(旧API)或DateTimeParseException(新API)。






