7
votes

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 linux system time?
(by editing some configuration file)

6
If you print out TimeZone.getDefault() what does that show you?Jon Skeet
minaret.biz/tips/timezone.html does this help?Sean
possible duplicate of How to set a JVM Timezone ProperlyNishant
Hardly a strict duplicate, @Nishant, but it’s a very helpful link, thank you.Ole V.V.

6 Answers

18
votes

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

5
votes

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.

4
votes

This code helped me.

TimeZone tzone = TimeZone.getTimeZone("Singapore");
// set time zone to default
tzone.setDefault(tzone);
2
votes
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.

2
votes

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
votes

use System.getCurrentTimeInMillis();

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