Format String to "00:00:00"

Asked

Viewed 722 times

3

I need this string to come out in 00:00:00 format currently it comes out: 5:4:1 for example, what I did was to do several ifs, but it is not efficient, and also it does not format when the 3 are below 10:

    long diffSeconds2 = long_hours / 1000 % 60;
    long diffMinutes2 = long_hours / (60 * 1000) % 60;
    long diffHours2 = long_hours / (60 * 60 * 1000) % 24;


    if (long_hours > 0) {
        if(diffSeconds2<10){
            str_testing = diffHours2 + ":" + diffMinutes2 + ":0" +diffSeconds2;

        }else if(diffMinutes2<10){
            str_testing = diffHours2 + ":0" + diffMinutes2 + ":" +diffSeconds2;
        }else if(diffHours2<10){
            str_testing = "0" + diffHours2 + ":" + diffMinutes2 + ":" +diffSeconds2;
        }
        //e se for os 3 abaixo de 10 teria que ficar: 00:00:00

3 answers

4


I believe it would be easier to put a formatter to String this way:

String hora = String.format("%02d:%02d:%02d", diffHours2, diffMinutes2, diffSeconds2);

I am saying that the value has to have 2 digits, so if there is only 1 digit it will complete with 0’s left. See on ideone.

But it didn’t seem to present the correct result, so an easier alternative is the following:

long yourmilliseconds = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");    
Date resultdate = new Date(yourmilliseconds);
System.out.println(sdf.format(resultdate));

That way you don’t need to make any account, see on ideone (

Reference: How to Transform currentTimeMillis to a readable date format.

  • That’s what I was looking for, thank you.

1

The logic you are using is not right because it tests each portion of the time in exclusion. It tests if the seconds are less than 10 to put the "0" but if that is the case you no longer see the rest, for they are in else if.

Can correct and use ternary operators to compress the code a little:

str_testing = (diffHours2<10? "0":"") + diffHours2 + ":" + 
              (diffMinutes2<10 ? "0":"") + diffMinutes2 + ":" + 
              (diffSeconds2<10 ? "0":"") + diffSeconds2;

So each part is analyzed separately from the others and just puts the "0" if less than 10.

1

Using the Formatter or String.format and assuming that long_horas is the time in milliseconds:

String horas = String.format("%tT", long_horas);

very simple since %tT amounts to %tH:%tM:%tS, that is, hour, minutes and seconds with two squares of argument passed in milliseconds.

Note: these methods, as well as the new Date interpret the time as milliseconds from 1 January 1970 0:00 (GMT) and therefore may occur problems regarding daylight saving time (for longer intervals) and similar...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.