java如何改时区
修改Java时区的几种方法
使用TimeZone类设置默认时区
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
这种方式会改变整个JVM的默认时区,影响所有时间操作。时区ID应采用IANA时区数据库格式(如"America/New_York")。
在特定日期操作中指定时区
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
Java 8及更高版本使用ZonedDateTime
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Paris"));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDate = now.format(formatter);
运行时指定JVM时区参数 在启动JVM时添加参数:
java -Duser.timezone=Asia/Tokyo YourApplication
Spring Boot应用中配置时区 在application.properties中添加:
spring.jackson.time-zone=Asia/Shanghai
数据库连接时指定时区 JDBC URL中添加时区参数:

String url = "jdbc:mysql://localhost:3306/db?useSSL=false&serverTimezone=UTC";
注意时区标识符应使用标准格式,完整列表可通过TimeZone.getAvailableIDs()获取。修改时区后建议验证时间显示是否符合预期,特别是涉及跨时区应用时需要考虑夏令时等因素。






