Java TimeZone

Recently, i was working with J2ME apps to get current time system. I faced several confusion when i tried to execute the code below :

long time = System.currentTimeMillis(); did not return the current hours on my computer, instead it return the hours based on Standard Time +0000 UTC. That means, no matter which machine or device you try to retrieve the current time, it always give you the time based on UTC. You can check the current UTC time on this link.

Since, i am in Melbourne/Australia, where my current timezone is UTC+11 and begin of the day light savings. One way to workaround to get the current time is using Calendar and Date in Java:

Calendar myCal= Calendar.getInstance (TimeZone.getTimeZone ("UTC"));

//The point here is to calculate the minutes based on UTC+11
Date date = new Date (myCal.getTime().getTime() + (11*60*60*1000));

long time = date.getTime();
int milliseconds = (int) (time % 1000);
int seconds = (int) ((time / 1000) % 60);
int minutes = (int) ((time / 60000) % 60);
int hours = (int) ((time / 3600000) % 24);

The above result will return in milliseconds when you use date.getTime() to get the value.

Result : 01:10:22 (based on the time i complie and run the code)

Useful Link. The world Clock.
Tips : If it is the end of Day Light Savings, you should -1, that means, UTC 10 instead of UTC 11.

Advertisements