Java apps by default takes the underlying Operating system’s timezone. If for some reason that is not available, then it defaults to UTC.
Lets see how to change the default timezone ?
- Externally by using the VM option -Duser.timezone
-Duser.timezone=America/New_York
- Or via code by setting the System property
user.timezone
.
System.setProperty("user.timezone", "America/New_York");
Note: This takes precedence over setting the timezone via VM options. But once set it will be cached and subsequent System.setProperty of user.timezone will not have any effect on the timezone. This should be set in the main class which is the entry point for the application before any date manipulation code else it will not have any effect on the JVM timezone.
System.setProperty("user.timezone","Africa/Dakar");
System.out.println(ZonedDateTime.now());
//Prints: 2022-08-24T03:11:28.138996900Z[Africa/Dakar]
System.setProperty("user.timezone","Asia/Dubai"); //No effect on Timezone
System.out.println(ZonedDateTime.now());
//Prints: 2022-08-24T03:11:28.139992900Z[Africa/Dakar] //No change to timezone
- Or via code by setting the default timezone using
java.util.TimeZone
class.
TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
Note: This takes precedence over the System.setProperty of user.timezone. Unlike System.setProperty this will overwrite the default timezone of the jvm everytime it is set.
TimeZone.setDefault(TimeZone.getTimeZone("Africa/Dakar"));
System.out.println(ZonedDateTime.now());
//Prints: 2022-08-24T03:08:01.483973Z[Africa/Dakar]
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Dubai"));
System.out.println(ZonedDateTime.now());
//Prints: 2022-08-24T07:08:01.485961600+04:00[Asia/Dubai]
TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
System.out.println(ZonedDateTime.now());
//Prints: 2022-08-23T23:08:01.492940900-04:00[America/New_York]