You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java技术问题:如何在Playlist类中将Song时长转为HH:MM:SS格式

解决播放列表总时长转换为HH:MM:SS格式的问题

首先,你的代码目前存在一个核心问题:直接将songDurationInHours、songDurationInMinutes、songDurationInSeconds的数值相加是错误的——这些字段是不同单位的时长,必须先统一转换为同一单位(比如秒)再累加,否则计算出的总时长完全不符合实际。

下面是修正后的完整实现方案:

步骤1:修正总时长的计算逻辑

先将每首歌的所有时长单位统一转换为秒,再累加得到总秒数:

public class Playlist {
    private List<Song> songs;
    private long totalPlaylistTime; // 建议存储总秒数,而非直接存储格式化后的字符串

    // 计算总时长(以秒为单位)
    public long getTotalDurationInSeconds() {
        long totalSeconds = 0;
        for (Song individualSong : getSongs()) {
            // 单位转换:小时→秒(×3600),分钟→秒(×60)
            totalSeconds += individualSong.getSongDurationInHours() * 3600L;
            totalSeconds += individualSong.getSongDurationInMinutes() * 60L;
            totalSeconds += individualSong.getSongDurationInSeconds();
        }
        setTotalPlaylistTime(totalSeconds);
        return totalSeconds;
    }
}

步骤2:将总秒数格式化为HH:MM:SS

新增一个方法,将总秒数转换为标准的HH:MM:SS格式,注意补零处理(比如1小时2分钟3秒要显示为01:02:03而非1:2:3):

方案A:手动计算格式化

// 在Playlist类中添加该方法
public String getFormattedTotalDuration() {
    long totalSeconds = getTotalDurationInSeconds();
    
    long hours = totalSeconds / 3600;
    long remainingSeconds = totalSeconds % 3600;
    long minutes = remainingSeconds / 60;
    long seconds = remainingSeconds % 60;
    
    // 使用String.format确保每个部分都是两位数字
    return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}

方案B:使用Java 8+的Duration类(更简洁)

如果你的项目使用Java 8或更高版本,可以借助Duration类简化单位转换:

// 在Playlist类中添加该方法
public String getFormattedTotalDuration() {
    long totalSeconds = getTotalDurationInSeconds();
    Duration duration = Duration.ofSeconds(totalSeconds);
    
    long hours = duration.toHours();
    long minutes = duration.toMinutes() % 60;
    long seconds = duration.getSeconds() % 60;
    
    return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}

额外优化建议

如果可以修改Song类,建议只存储总秒数这一个字段,而不是分开存储小时、分钟、秒——这样能避免单位转换错误,代码也更简洁:

public class Song {
    private long totalDurationInSeconds;

    public Song(long hours, long minutes, long seconds) {
        this.totalDurationInSeconds = hours * 3600L + minutes * 60L + seconds;
    }

    public long getTotalDurationInSeconds() {
        return totalDurationInSeconds;
    }
}

此时Playlist类的计算逻辑可以进一步简化,直接累加每首歌的总秒数即可。

内容的提问来源于stack exchange,提问作者KingSkitz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:24:15