Format String for "00:00:00"

3

I need this string to output in the format 00:00:00 currently it goes out: 5: 4: 1 For example, what I did was do several ifs, but it is not efficient, and it also 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
    
asked by anonymous 26.09.2017 / 02:49

3 answers

4

I think it would be easier to put a String formatter like this:

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

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

But I did not seem to present the correct result, so another easier alternative is:

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 do not need to do any accounts, check out ideone (

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

    
26.09.2017 / 03:16
1

The logic you are using is not right because it tests every portion of the time at exclusion. If the seconds are less than 10 to "0" but if it is the case you do not see the rest because they are else if .

You can fix and use ternary operators to compress the code a bit:

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

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

    
26.09.2017 / 03:02
1

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

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

Pretty simple since %tT is equal to %tH:%tM:%tS , that is, hour, minutes, and seconds with two argument houses passed in milliseconds.

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

    
26.09.2017 / 13:54