有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

格式化Java字符串时间格式化

有没有办法不用if ( hours > 0 )就可以做到这一点?我觉得必须有一种方法来指示数字的条件显示,但我在javadocs或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 );
    }
}

谢谢


共 (2) 个答案

  1. # 1 楼答案

    无法使用format(),只需修剪前导零:

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

    如果小时和分钟均为零,则此代码还会对分钟进行微调。如果你总是想要会议记录,请从这段代码中删除(00:)?

  2. # 2 楼答案

    我认为没有时间,代码不会灵活>;0条件。 修剪也是一个不错的选择

    /**
    * 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";
       }
    
    }
    

    检查上面的代码,返回小时-分钟-秒格式,如果需要,也可以添加分钟条件