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

About Charles Ling
Web/Android/IPhone Developer. Very very interested in Web Architecture, Web Standard and and how to use Web to improve human social life and doing cool stuff.

One Response to Java TimeZone

  1. Evans says:

    Nice tip!

    The last time I developed in J2ME was 5 years ago – but I still enjoy seeing people working with it though.

    Good luck!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: