How to set java timezone?

前端 未结 6 1382
囚心锁ツ
囚心锁ツ 2021-01-05 11:53

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

6条回答
  •  清酒与你
    2021-01-05 12:27

    Avoid the need

    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.

    If you can’t avoid the need

    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
    

    Link

    Oracle tutorial: Date Time explaining how to use java.time.

提交回复
热议问题