Grumblesaurus
Grumblesaurus

Reputation: 3119

Java String Time Formatting

Is there a way to do this without the if ( hours > 0 ) ? I feel like there must be a way to indicate a conditional display for the digit, but I couldn't find it in the javadocs or with google.

public String getLengthDisplay () {
    int hours = getLength() / 3600;
    int minutes = ( getLength() % 3600 ) / 60;
    int seconds = getLength() % 60;

    if ( hours > 0 ) {
        return String.format ( "%d:%02d:%02d", hours, minutes, seconds );
    } else {
        return String.format ( "%d:%02d", minutes, seconds );
    }
}

Thanks!

Upvotes: 1

Views: 58

Answers (2)

Prahlad Rao
Prahlad Rao

Reputation: 34

I don't think the code will be flexible without the hour > 0 condition. Trimming is also a good option.

/**
* This method is used to get the Execution Time
* by calculating the difference between StartTime and EndTime
* 
* @param StartTime Execution Start Time
* @param EndTime Execution End Time
* @return Total Execution Time
*/
 private static String ExecutionTime(String StartTime, String EndTime){

   LocalTime fromDateTime = LocalTime.parse(StartTime);
   LocalTime toDateTime = LocalTime.parse(EndTime);

   LocalTime tempDateTime = LocalTime.from( fromDateTime );

   long hours = tempDateTime.until( toDateTime, ChronoUnit.HOURS);
   tempDateTime = tempDateTime.plusHours( hours );

   long minutes = tempDateTime.until( toDateTime, ChronoUnit.MINUTES);
   tempDateTime = tempDateTime.plusMinutes( minutes );

   long seconds = tempDateTime.until( toDateTime, ChronoUnit.SECONDS);


   if(hours > 0){
       return hours + "h " +minutes + "min " + seconds + "s";
   }else{
       return minutes + "min " + seconds + "s";
   }

}

Check the above code, which return Hour Minute Second format, you can add minute condition also if needed.

Upvotes: 1

Bohemian
Bohemian

Reputation: 424953

There's no way with format(), but just trim leading zeros:

return String.format("%d:%02d:%02d", hours, minutes, seconds)
    .replaceAll("^0:(00:)?", "");

This code also trims the minutes if both hour and minute are zero. If you always want the minutes, delete (00:)? from this code.

Upvotes: 1

Related Questions