如何强制 Spring Boot JVM 进入 UTC 时区?

2022-09-01 16:20:46

我看到强制 Java 时区为 GMT/UTC

我试过了

  • mvn spring-boot:run -Dexec.args=“-Duser.timezone=GMT”
  • mvn spring-boot:run -Dexec.args=“-Duser.timezone=UTC”
  • user.timezone=UTCconfig/application.properties
  • user.timezone=GMT
  • 在 pom.xml:

        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <properties>
                  <spring-boot.run.jvmArguments>-Duser.timezone=UTC</spring-boot.run.jvmArguments>
                </properties>
            </configuration>
        </plugin>
    
  • mvn spring-boot:run -Dspring-boot.run.jvmArguments=“-Duser.timezone=UTC”

但它打印出来

System.out.println(TimeZone.getDefault());

sun.util.calendar.ZoneInfo[id=“America/New_York”,offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]]

Spring Boot 1.5.19, Java 8


答案 1

我认为您可以在应用程序级别上设置应用程序的时区。我认为这个链接会帮助你。https://www.onlinetutorialspoint.com/spring-boot/how-to-set-spring-boot-settimezone.html

因此,您需要做的是将“@PostConstruct”注释添加到“@SpringBootApplication”注释所在的主类中,并在那里添加时区设置方法。下面是一个示例。

@SpringBootApplication
public class HellotimezoneApplication {

    public static void main(String[] args) {
        SpringApplication.run(HellotimezoneApplication.class, args);
    }

    @PostConstruct
    public void init(){
      // Setting Spring Boot SetTimeZone
      TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    }

}

希望这可以帮助你!


答案 2

使用 spring-boot.run.jvmArguments 属性,如果你想将 JVM 选项从 Maven Spring Boot Plugin 传递到分叉的 Spring Boot 应用程序:

<properties>
  <spring-boot.run.jvmArguments>-Duser.timezone=UTC</spring-boot.run.jvmArguments>
</properties>

这等效于命令行语法:

mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Duser.timezone=UTC"

或者运行完全打包的 Spring Boot 应用程序时:

java -Duser.timezone=UTC -jar app.jar

推荐