# 场景

在产品用户记录列表里,后端返回了一串用户的数据,其中包括 用户的 姓名、头像地址、ip地址、距上次的浏览时间点的时长。 其中拿到的这个时长是以为单位,需要前端写个工具类来格式化时长。

# 需求分析

  • 默认传入一个参数: 时长
  • 最多显示三个时间单位,且这三个单位是相连的,例如x天x时x分 x时x分x秒
  • 如果出现单位刚好出现整数0,则不显示。如1天0时则显示1天,1时0分显示1时

# 扩展需求

  • 扩展一个参数option,类型是Object,目的是让开发者自由定义其中的配置。

# 代码实现

function formatTime(duration, option = { calcCell: '毫秒', DD: '天', HH: '时', mm: '分', SS: '秒' }) {
    const { calcCell, DD, HH, mm, SS } = option;
    calcCell === '秒' && (duration = duration / 1000)
    calcCell === '分钟' && (duration = duration / 1000 / 60)

    let int = parseInt(duration)
    if (isNaN(int)) {
        return `1分钟内`
    }

    let val = ``

    // 天
    const d = Math.floor(int / (3600 * 24))
    if (d >= 1) {
        val += `${d}${DD}`
    }

    // 时
    int = int % (3600 * 24)
    const h = Math.floor(int / 3600)
    if (h >= 1) {
        val += `${h}${HH}`
    }

    // 分
    int = int % 3600
    const m = Math.floor(int / 60)
    if (m >= 1) {
        val += `${m}${mm}`
    }

    // 秒
    int = int % 60
    if (int >= 1 && d < 1) {
        val += `${int}${SS}`
    }

    return val
}

# 测试用例

console.log(formatTime(90000)); // 1天1时
console.log(formatTime(93783)); // 1天2时3分
console.log(formatTime(86400)); // 1天
console.log(formatTime(86406)); // 1天
console.log(formatTime(93603)); // 1天2时

console.log(formatTime(10800)); // 3时
console.log(formatTime(11040)); // 3时4分
console.log(formatTime(11042)); // 3时4分2秒
console.log(formatTime(11041)); // 3时4分1秒
console.log(formatTime(11040)); // 3时4分

console.log(formatTime(242)); // 4分 2秒
console.log(formatTime(240)); // 4分 秒
console.log(formatTime(2)); // 分 2秒
console.log(formatTime()); // 1分钟内