现象
程序进行迁移时,发现输出的时间差了8个小时
分析
1 2 3 4 5
| FROM openjdk:8-alpine
COPY ./target/retire-manage-0.0.1-SNAPSHOT.jar app/retire-manage.jar
ENTRYPOINT ["java", "-jar" , "/app/retire-manage.jar", "-Duser.timezone=GMT+8"]
|
其实dockerfile中已经指定了”-Duser.timezone=GMT+8”,但是没有生效。
在程序中尝试打印如下日志,发现打印的是GMT的时间
1 2
| LocalDateTime now = LocalDateTime.now(); System.out.println("Current time in GMT+8: " + now.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
|
解决
在 Java 代码中显式设置时区
你可以通过以下代码来设置 JVM 的默认时区为日本时区。
在启动类中设置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import java.util.TimeZone;
@SpringBootApplication public class Application implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(Application.class, args); }
@Override public void run(String... args) throws Exception { TimeZone.setDefault(TimeZone.getTimeZone("Asia/Tokyo")); } }
|