How to set timezone to UTC in Play Framework 2.0 f

2019-03-21 16:46发布

问题:

We'd like our Play Framework 2.0 Scala applications to handle all date and time information in UTC, both in the app servers and in MySQL database servers.

The trick is:

  • Without changing deployment environment
  • Without changing CI (testing) environment
  • Without changing local (dev) environment

Is there a standard best practice to do this? We want the tests to run in UTC, without having to pass -Duser.timezone=GMT on all commandlines. Ditto for bringing up servers with play start.

回答1:

This was easier than we'd expected.

First, in application.conf, configure the JDBC URL with the parameters as described on another StackOverflow question:

# Set MySQL Connector/J to use UTC server connection and time conversions
#   see https://stackoverflow.com/questions/10488529/gettimestamp-does-timezone-converstion-twice-in-mysql-jdbc-connector
db.default.url="jdbc:mysql://localhost/database?useGmtMillisForDatetimes=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&useTimezone=true&serverTimezone=UTC"

Second, in Build.scala, set the Java system property and the default:

// Setting this property here forces the JVM to run in UTC time, 
// both for test (`play test`) and development (`play start`) modes, 
// but not for production (`play dist`).
System.setProperty("user.timezone", "GMT")
TimeZone.setDefault(TimeZone.getTimeZone("GMT"))

These two changes together will handle both test (play test) and development (play start) modes.

For production (play dist), one must still set the property before launch. For example, by:

  1. Editing the generated start script to add export _JAVA_OPTIONS=-Duser.timezone=GMT
  2. Invoking the start script with -Duser.timezone=GMT
  3. Launching within an existing JVM after calling System.setProperty("user.timezone", "GMT")