How to set java timezone?

前端 未结 6 1385
囚心锁ツ
囚心锁ツ 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:03

    If you want to change the time zone programmatically then you can use:

    TimeZone.setDefault(TimeZone.getTimeZone("UTC"))
    

    I prefer this method because it doesn't rely on people remembering to run my code with the correct time zone arguments.

    0 讨论(0)
  • 2021-01-05 12:04

    use System.getCurrentTimeInMillis();

    and then take a calendar instance and set Your time..

    0 讨论(0)
  • 2021-01-05 12:09

    You can use TimeZone.setDefault(..) when your application starts, or pass the timezone as command-line argument: -Duser.timezone=GMT

    0 讨论(0)
  • 2021-01-05 12:14

    This code helped me.

    TimeZone tzone = TimeZone.getTimeZone("Singapore");
    // set time zone to default
    tzone.setDefault(tzone);
    
    0 讨论(0)
  • 2021-01-05 12:16
    Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
    Date myDate = calendar.getTime();
    System.out.println(myDate);
    

    Is this code printing the right date/time? Else, there's some other problem.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题