java时区设置失效的坑
linux上部署了springboot项目,但是时间有问题,找到解决方法
可以在jvm启动参数上设置-Duser.timezone=GMT+8
但是略麻烦,因此在项目启动的时候设置
代码如下
public static void main(String[] args) {
System.out.println(System.getProperty("user.timezone")); //打印'UTC'
//1
System.setProperty("user.timezone", "GMT+8");
//2
TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
System.out.println(System.getProperty("user.timezone")); //打印'UTC'
SpringApplication.run(DemoApplication.class, args);
}
结果时间还是没有改正过来,后来发现先设置了时区再启动的项目,可能就没有失效
正确代码如下,1/2方式都可以
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
System.out.println(System.getProperty("user.timezone")); //打印'UTC'
//1
System.setProperty("user.timezone", "GMT+8");
//2
TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
System.out.println(System.getProperty("user.timezone")); //打印'UTC'
}