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
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.
use System.getCurrentTimeInMillis();
and then take a calendar instance and set Your time..
You can use TimeZone.setDefault(..)
when your application starts, or pass the timezone as command-line argument: -Duser.timezone=GMT
This code helped me.
TimeZone tzone = TimeZone.getTimeZone("Singapore");
// set time zone to default
tzone.setDefault(tzone);
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.
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.