Polar Polar - 26 days ago 11
Java Question

Convert Hours and Minutes into Milliseconds and return into HH:mm:ss Format

Using

TimeUnit
I wanted to Convert
Hours
and
Minutes
into
Milliseconds
with the below code:

int hours = 01, minutes = 0;
long milliseconds = TimeUnit.SECONDS.toMillis(TimeUnit.HOURS.toSeconds(hours) + TimeUnit.MINUTES.toSeconds(minutes));


Works Fine with
3600000
milliseconds

And using
SimpleDateFormat
to return into
HH:mm:ss
format:

SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
Date date = new Date(milliseconds);
String returnFormat = formatter.format(date); //Final Result.


and this give me a result of
09:59:59
which is not the expected output.

I am confused, what's wrong with the code above? I am expecting
01:00:00
output.

UPDATE:

Actually I am using the above code to create a simple countdown timer using
Handler post.delayed
function.

...
@Override
public void run() {
milliseconds -= 1000; //Remove 1 Seconds
handler.postDelayed(this,1000); //Delay in 1 Seconds
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); //Create Time Formatting
Date date = new Date(milliseconds); //Put the milliseconds into Format
String returnFormat = formatter.format(date));
Log.w("COUNTDOWN", returnFormat);
}

Answer

This happens because of your timezone is different. By making the timezone GMT you will be able to gain the expected result. Use the following code snippet.

SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
Date date = new Date(milliseconds);
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
String returnFormat = formatter.format(date); //Final Result.
System.out.println(returnFormat);
Comments