Convert milliseconds to hour / minute / seconds on Android

1

Someone could see me an example of the CountDownTimer class for an hour / minute / seconds format, thanks.

I tried this but it does not work

contador.setText(""+String.format(FORMAT,
                 TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
                 TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
                         TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
                 TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
                         TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
  

The problem is that MILLISECONDS marks it in red. just give me the option   of MILLISECOND but, after this, I do not appear to Hours.

I work with Android version 5.1.

    
asked by Ashley G. 15.08.2017 в 01:20
source

2 answers

1

You have several problems, the first one without a doubt is to define the correct import that should be:

import java.util.concurrent.TimeUnit;

This to use the class and its constant:

 TimeUnit.MILLISECONDS

The second is that it is incorrectly calculated the hours, the necessary argument is missing. The format that I add must be the correct one for the format you want:

String FORMAT = "%02d/%02d/%02d";
String  myTime =  String.format(FORMAT,
                //Hours
                TimeUnit.MILLISECONDS.toHours(millisUntilFinished) -                        TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(millisUntilFinished)),
                //Minutes
                TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) -
                        TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
                //Seconds
                TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
                        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));

Another method that is simpler to obtain the desired format would be this:

Date date = new Date(millisUntilFinished);
SimpleDateFormat formatter = new SimpleDateFormat("HH/mm/ss");
String myTime = formatter.format(date );

For both options, as an example a time defined as 05:25:25 PM would be obtained:

17/25/25
    
answered by 16.08.2017 / 19:48
source
2

The class you're looking for is java.util.concurrent.TimeUnit . You are probably using the class TimeUnit of the% package android.icu.util that does not contain MILLISECONDS .

Change:

import android.icu.util.TimeUnit;

By:

import java.util.concurrent.TimeUnit;
    
answered by 16.08.2017 в 02:50