My system time differs from what java\'s new Date() tells (+ 4 hours),
so I think it\'s because some java settings.
How can I make java time to be always as my linu
Make your date and time code independent of the JVM’s time zone setting. The setting is unreliable anyway, so not using it will be for the best regardless.
For a time zone.
ZoneId z = ZoneId.of( "Asia/Japan" ) ; // Or use `ZoneId.systemDefault()` for the JVM’s current default time zone. The JVM’s default may or may not match that of the host OS’ current default time zone.
ZonedDateTime zdt = ZonedDateTime.now( z ) ; // Capture the current moment as seen in a particular time zone.
For UTC (an offset of zero).
OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;
Yes, I know that printing an old-fashioned java.util.Date
and thereby implicitly invoking its toString
method causes it to use the time zone setting for rendering the string to be printed. You should no longer use the Date
class, though. It’s poorly designed. The confusing trait of using the JVM time zone and thus pretending that a Date
holds a time zone is just one of its many bad sides. Use java.time, the modern Java date and time API, for your date and time work.
Set the environment variable TZ
in Unix to the desired time zone ID. For example this worked for me on my Mac:
export TZ=Etc/UTC
java -cp /Your/class/path your.package.YourMainClass
Oracle tutorial: Date Time explaining how to use java.time.